使用PreparedStatement 防止SQL注入
getConnection()
public static Connection getConnection(){
Connection conn = null;
try {
InputStream is = JDBC_curd.class.getClassLoader().getResourceAsStream("jdbc.properties");
Properties pros = new Properties();
pros.load(is);
//1.读取配置文件中的4个基本信息
String url = pros.getProperty("url");
String user = pros.getProperty("user");
String password = pros.getProperty("password");
String driverClass = pros.getProperty("driverClass");
//2.加载驱动
Class.forName(driverClass);
//3.获取连接
conn = DriverManager.getConnection(url, user, password);
// System.out.println(conn);
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
return conn;
}
closeConnection
public static void closeConnection(Connection conn,PreparedStatement ps){
try {
if (ps!=null)
ps.close();
if(conn!=null)
conn.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
url=jdbc:mysql://localhost:3306/atguigu?characterEncoding=utf8
user=root
password=sa
driverClass=com.mysql.jdbc.Driver