数据库连接被用于向数据库服务器发送命令和SQL语句,并接受数据库服务器返回的结果。其实一个数据库连接就是一个Socket连接。
在java.sql包中有3个接口分别定义了对数据库的调用的不同方式:
- Statement:用于执行静态SQL语句并返回它所生成的结果的对象。
- PrepatedStatement:SQL语句被预编译并存储在此对象中,可以使用此对象多次高效地执行该语句。
- CallableStatement:用于执行SQL存储过程。
使用Statement的弊端,需要拼写sql语句,并且存在SQL注入(SQL注入是利用某些系统没有对用于输入的数据进行充分的检查,而在用户输入数据中注入非法的SQL语句段或命令(如:SELECT user,password FROM user_table WHERE user='a' OR 1 = 'AND' password = 'OR' '1' = '1'),从而利用系统的SQL引擎完成恶意行为的做法。)的问题。对于java而言,只需要用PreparedStatement(从Statement扩展而来)取代Statement就可以了。
数据的简单添加操作
package com.JDBCStudy3.PreparedStatement.crud; import java.io.IOException; import java.io.InputStream; import java.sql.Connection; import java.sql.Date; import java.sql.DriverManager; import java.sql.SQLException; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Properties; import com.mysql.jdbc.PreparedStatement; /* * 使用PrepareStatement来替代Statement,实现对数据表的增删改查操作。 * 增删改查 * */ public class PrepareStatements { // 向customers表中添加一条记录 public void testInsert() { Connection coon = null; PreparedStatement ps = null; try { // 1、读取配置文件中的4个基本信息 InputStream is = PrepareStatements.class.getClassLoader().getResourceAsStream("jdbc.properties"); Properties pros = new Properties(); pros.load(is); String user = pros.getProperty("user"); String password = pros.getProperty("password"); String url = pros.getProperty("url"); String driverClass = pros.getProperty("driverClass"); // 2、加载驱动 Class.forName(driverClass); // 3、获取连接 coon = DriverManager.getConnection(url, user, password); // System.out.println(coon); // 4、预编译sql语句,返回PreparedStatement的实例 String sql = "insert into customers(name,email)values(?,?,?)";// ?占位符 ps = (PreparedStatement) coon.prepareStatement(sql); // 5、填充占位符 ps.setString(1, "娜扎"); ps.setString(2, "nazha@gmail.com"); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-mm-dd"); java.util.Date date = sdf.parse("1000-01-01"); ps.setDate(3, new Date(date.getTime())); // 6、执行操作 ps.execute(); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { // 7、资源的关闭 try { if (ps != null) ps.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { if (coon != null) coon.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }
jdbc.properties
user=root
password=root
url=jdbc:mysql://localhost:3306/MySQL
driverClass=com.mysql.jdbc.Driver