JDBC学习一:
前言
记录一下JDBC的学习笔记,MySQL版本5.7,驱动版本5.1.47一、注册驱动与加载驱动
1. 注册驱动的方式如下:
DriverManager.registerDriver(new com.mysql.jdbc.Driver());
//不建议使用,会导致注册两次,并且强烈依赖mysql的jar包
2. 加载驱动的方式如下:
Class.forName("com.mysql.jdbc.Driver");
//实际运用中更推荐使用这种方式
二、获取连接Connection
1. 方式一:
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/xxx", "root", "root");
2. 方式二:
Properties info = new Properties();
//创建info对象
info.setProperty("user","root"); //用户名
info.setProperty("password","root"); //密码
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/xxx", info);
//在连接对象中传入info对象
3. 方式三:
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/xxx?user=root&password=root");
//在地址上拼接用户名和密码
注意事项:
当运行报WARN: Establishing SSL connection without server’s identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn’t set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to ‘false’. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.的警告时,在连接的url后加上useSSL=true
如:“jdbc:mysql://localhost:3306/test_sql?useUnicode=true&characterEncoding=utf-8&useSSL=true”
三、得到执行sql语句的对象Statement
代码如下(示例):
Statement stmt=conn.createStatement();
四、执行sql语句,并返回结果
1. 查询语句使用executeQuery()
ResultSet res = stmt.executeQuery("select * from xxx");
2. 增删改操作,使用executeUpdate()
int i = statement.executeUpdate("delete from users where id=5"); //删除操作
//返回受影响的行数(int)
int i = statement.executeUpdate("insert into users values (5,'Tim',20,1,30,'10005')"); //插入操作
int i = statement.executeUpdate("update users set name='tom' where id=1"); //修改操作
3. 执行任意sql语句的方法,execute()
返回的是布尔值,仅在执行sql语句,并且有返回值时返回true,其他都返回false(一般不用)。
五、处理结果集(查询得到的ResultSet)
1. getObject(int columnIndex)
res.getObject(1);
//可以传入数据库列表的索引值,注意:数据库的索引是从1开始的
2. getObject(String columnLabel)
res.getObject("id");
//可以传入数据库列表的名称
3. 把结果放入封装的对象中
根据结果集的列表创建对应对象,然后取出结果集中的值设置为对象属性值,并存入集合中:
List<User> list = new ArrayList<>();
while(resultSet.next()){
User user = new User();
user.setId(resultSet.getInt("id"));
user.setName(resultSet.getString("name"));
user.setAge(resultSet.getShort("age"));
user.setStatus(resultSet.getInt("status"));
user.setScore(resultSet.getShort("score"));
user.setAccountid(resultSet.getString("accountid"));
list.add(user);
}
User对象的创建如下:
public class User {
//自定义对象的属性类型与数据库的类型对应
private int id;
private String name;
private short age;
private int status;
private short score;
private String accountid;
public User() {
}
public User(int id, String name, short age, int status, short score, String accountid) {
this.id = id;
this.name = name;
this.age = age;
this.status = status;
this.score = score;
this.accountid = accountid;
}
//此处省略get和set方法,以及toString方法
}
总结
以上就是jdbc第一次的笔记总结,记录了如果连接数据库,增删改查操作,以及查询后的结果如果处理。