时间:2021-07-01 10:21:17 帮助过:15人阅读
import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.SQLException; public class TestJDBC { public static void main(String[] args) { try { Class.forName("com.mysql.jdbc.Driver"); } catch (ClassNotFoundException e) { e.printStackTrace(); } String sql = "insert into hero values(null,?,?,?)"; try (Connection c = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/how2java?characterEncoding=UTF-8","root", "admin"); // 根据sql语句创建PreparedStatement PreparedStatement ps = c.prepareStatement(sql); ) { // 设置参数 ps.setString(1, "提莫"); ps.setFloat(2, 313.0f); ps.setInt(3, 50); // 执行 ps.execute(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
Statement 需要进行字符串拼接,可读性和维护性比较差
String sql = "insert into hero values(null,"+"‘提莫‘"+","+313.0f+","+50+")";
PreparedStatement 使用参数设置,可读性好,不易犯错
String sql = "insert into hero values(null,?,?,?)";
public class TestJDBC { public static void main(String[] args) { try { Class.forName("com.mysql.jdbc.Driver"); } catch (ClassNotFoundException e) { e.printStackTrace(); } String sql = "insert into hero values(null,?,?,?)"; try (Connection c = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/how2java?characterEncoding=UTF-8","root", "admin"); Statement s = c.createStatement(); PreparedStatement ps = c.prepareStatement(sql); ) { // Statement需要进行字符串拼接,可读性和维修性比较差 String sql0 = "insert into hero values(null," + "‘提莫‘" + "," + 313.0f + "," + 50 + ")"; s.execute(sql0); // PreparedStatement 使用参数设置,可读性好,不易犯错 // "insert into hero values(null,?,?,?)"; ps.setString(1, "提莫"); ps.setFloat(2, 313.0f); ps.setInt(3, 50); ps.execute(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }