JDBC连接数据库的要素:
1、数据库URL
2、用户名
3、密码
4、Connection对象
Connection connection = null;
PreparedStatement preparestatement = null;
//1、读取配置文件
InputStream is=ClassLoader.getSystemClassLoader().getResourceAsStream("jdbc.properites");
Properties pros = new Properties();
pros.load(is);
//2、获取数据库连接要素
String user = pros.getProperty("user");
String password = pros.getProperty("password");
String url = pros.getProperty("url");
String driverClass = pros.getProperty("driverClass");
//3、加载驱动
Class.forName(driverClass);
//4、获取连接
connection=DriverManager.getConnection(url, user, password);
//sql语句
String sql="insert into customers (name,email,birth) values (?,?,?)";//?占位符
//5、通过Connection对象调用PreparedStatement方法预编译SQL语句,获得PreparedStatement对象
preparestatement=connection.prepareStatement(sql);
//6、占位符赋值,Java索引从0开始,sql索引从1开始,注意Java与sql数据类型的对应关系
preparestatement.setString(1, "哪吒");
preparestatement.setString(2, "nezha@gmail.com");
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
java.util.Date date=sdf.parse("2022-05-13");
preparestatement.setDate(3,new Date(date.getTime()));//注意sql的Date与java的Date数据类型差别
//7、执行sql语句
preparestatement.execute();
//8、关闭资源
preparestatement.close();
//9、关闭数据库连接
connection.close();
其中jdbc.properties内容为:
user=root
password=root
url=jdbc:mysql://localhost:3306/test
driverClass=com.mysql.jdbc.Driver