public class TestJdbc2 {
public static void main(String[] args) throws ClassNotFoundException, SQLException {
//配置信息
//?useUnicode=true&characterEncoding=utf-8 解决中文乱码
String url ="jdbc:mysql://localhost:3306/jdbc?useUnicode=true&characterEncoding=utf-8";
String username="root";
String password="123456";
//1.加载驱动
Class.forName("com.mysql.jdbc.Driver");
//2.连接数据库
Connection connection = DriverManager.getConnection(url, username, password);
//3.编写SQL
String sql="insert into users(id, name, password, email, birthday)values (?,?,?,?,?)";
//4.预编译
PreparedStatement preparedStatement = connection.prepareStatement(sql);
preparedStatement.setInt(1,3);//给第一个占位符赋值 1
preparedStatement.setString(2,"huhao");//给第二个占位符赋值 1
preparedStatement.setString(3,"123456");//给第三个占位符赋值 1
preparedStatement.setString(4,"48@qq.com");//给第四个占位符赋值 1
preparedStatement.setDate(5,new Date(new java.util.Date().getTime()));//给第五个占位符赋值 1
//执行SQL
int i = preparedStatement.executeUpdate();
if(i>0){
System.out.println("插入成功!");
}
preparedStatement.close();
connection.close();
}
}
原文:https://www.cnblogs.com/huhao2000/p/11989344.html