目录
1. 创建数据库源对象
2. 设置URL/User/PassWord
3. 建立连接
4. 构造要执行的SQL语句
5. 执行
6. 结束释放相关资源
DataSource dataSource = new MysqlDataSource();
((MysqlDataSource)dataSource).setURL("jdbc:mysql://127.0.0.1:3306/databaseName?characterEncoding=utf8&useSSL=false");
((MysqlDataSource)dataSource).setUser("root");
((MysqlDataSource)dataSource).setPassword("SHANhaonan521");
Connection connection = dataSource.getConnection();
String sql = "select * from message";
PreparedStatement statement = connection.prepareStatement(sql);
//1. 第一种:删除修改语句使用,返回的值是这次SQL操作影响到的行数
int n = statement.executeUpdate();
//2. 第二种:查询语句使用,返回值是返回的临时表数据
ResultSet resultSet = statement.executeQuery();
ResultSet对象 被称为“结果集”,他代表复合SQL语句条件的所有行,可以通过getXXX方法对这些行的数据进行访问。如果要进行遍历可以使用 while (resultSet.next()) 进行遍历。例子:
while (resultSet.next()){ String name = resultSet.getString("name");int age = resultSet.getInt("age");
}
statement.close();
connection.close();
注意要先关闭statement,再关闭connection