jdbc连接数据库
public class DbUtil {
static{
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
public static Connection getConnection(){
String url = "jdbc:mysql://127.0.0.1:3306/test?serverTimezone=GMT%2B8";
String account = "root";
String pwd = "root";
Connection connection = null;
try {
connection = DriverManager.getConnection(url,account,pwd);
} catch (SQLException e) {
e.printStackTrace();
}
return connection;
}
使用Db.Util工具类插入数据的两种方法。
String sql = "insert into student(name,phone) values (?,?)";
PreparedStatement ps = connection.prepareStatement(sql);
ps.setString(1,firstname);
ps.setString(2,lastname);
ps.executeUpdate();
占位。setString表示第几个占位符。从1开始。
或者采用直接sql拼接。
String sql = "insert into student(name,phone) values('"+firstname+"','"+lastname+"')";
PreparedStatement ps = connection.prepareStatement(sql);
ps.executeUpdate();
setString可能会报的两个错误。
Parameter index out of range(0 < 1) 代表索引从1开始。
Parameter index out of range(1 > number of parameters,which is 0) 代表找不到占位符就是那个 ?号。
下面这个错记得加