一:环境配置
官网下载mysql驱动,并存在模块新建目录下,并设置相应的影响范围
下载网址:http://dev.mysql.com/downloads/connector/j/
二:获取数据库连接
1:直接连接
//将mysql加载到内存中,由于版本不匹配原因该出加了.cj,原应为"com.mysql.jdbc.Driver"(这条可加可不加)
Class.forName("com.mysql.cj.jdbc.Driver");
//设置相应的URL为固定格式 jdbc:mysql://[host][,failoverhost...][:port]/[database] [?propertyName1][=propertyValue1][&propertyName2][=propertyValue2]...
String Url = "jdbc:mysql://localhost:3306/my_jdbc?useServerPrepStmts = true & cachePrepStmts = true";
//MySQL账户用户名
String UserName = "root";
//MySQL账户密码
String PassWord = "*********";
//获取连接对象
Connection connection = DriverManager.getConnection(Url, UserName, PassWord);
2:数据库连接池(com.alibaba.druid)
Properties properties = new Properties();
//加载配置文件,文件为相对路径
properties.load(new FileInputStream("src/DruidJDBC.properties"));
//固定格式
DataSource ds = DruidDataSourceFactory.createDataSource(properties)
//获取连接对象
Connection connection = ds.getConnection();
//配置文件部分信息,不用加分号,具体可参考相应文档
driverClassName=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/my_jdbc?useServerPrepStmts = true & cachePrepStmts = true
username=root
password=*****
三:定义SQL语句
String sql="select * from custom";
四:获取SQL执行对象
1:statement(不安全,存在SQL注入问题)
//获取SQL执行对象
Statement statement = connection.createStatement();
//执行Sql语句
//执行DQL 返回ResultSet对象
statement.executeQuery(sql);
//执行DML,DDL语句返回影响行数
statement.executeUpdate(sql);
/*
*result 对象会接收执行完查询语句返回的表
*/
//result.next()会读取下一行数据,若存在则返回false,通过getXXX()方法刻返回读取的数据,XXX为
//数据类型,传递的数据可以为索引,也可以为该列数据的字段名称
while (resultSet.next()) {
int id = resultSet.getInt("id");
String name = resultSet.getString("name");
int age = resultSet.getInt("age");
account = new Account(id, name, age);
AccountList.add(account);
}
2:PrepareStatement(为statement子类,可以防止SQL注入,并且执行效率也更高)
//定义SQL语句
String sql1 = "update text1 set age=22 where id= ? or id =? ";
/**
* 获取执行SQL语句的对象,preparestatement可以将SQL语句中的 ? 占位符通过setXXX(int index,XXX value)方法替换为指定的数据,
* 可以提高执行效率,与执行处理需要在URL语句中添加useServerPrepStmts = true & cachePrepStmts = true完成
*/
PreparedStatement pstm = connection.prepareCall(sql1);
int id1=1;
int id2=2;
//第一批
pstm.setInt(1,id1);
pstm.setInt(2,id2);
System.out.println(pstm);
pstm.addBatch();
//第二批
pstm.setInt(1,3);
pstm.setInt(2,4);
pstm.addBatch();
//执行所有批次
pstm.executeBatch();
五:关闭各种对象
//先开启的先关闭
result。close();
pstm.close();
connection.close();
六:总结(JDBC连接步骤)
1:加载如com.mysql.jdbc.Driver,定义URL,username,password 连接数据库,获取连接数据库对象。
2:定义SQL语句
3:获取执行SQL的对象(如:statement,preparestatement)
4:执行SQL语句
5:关闭资源