DAY2——JDBC操作数据库
1 JDBC概述
1.1 JDBC
JDBC(Java Data Base Connectivity,java数据库连接)是一种用于执行SQL语句的Java API,可以为多种关系数据库提供统一访问,它由一组用Java语言编写的类和接口组成。JDBC提供了一种基准,据此可以构建更高级的工具和接口,使数据库开发人员能够编写数据库应用程序。
1.2 数据库驱动
我们安装好数据库之后,我们的应用程序也是不能直接使用数据库的,必须要通过相应的数据库驱动程序,通过驱动程序去和数据库打交道。其实也就是数据库厂商的JDBC接口实现,即对Connection等接口的实现类的jar文件。
可前往mysql官网下载所需版本,附上链接我是链接。
2 使用JDBC的步骤
2.1 加载驱动
将下载好的驱动加载入project,具体步骤如下:
新建lib文件夹→右键点击→Add as library→选择驱动包
2.2 创建数据库连接
这里将用到两个接口:Driver接口和Connection接口,概念可自行百度,作为编程人员,只要会使用即可。附上使用代码:
public static Connection getConnection() {
try {
Class.forName("com.mysql.jdbc.Driver");
//2创建连接
Connection connection = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/user?useSSL=true&serverTimezone=GMT&characterEncoding=utf-8&user=root&password=wei130303");
return connection;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
2.3 写sql语句
由于上一步骤已成功连接上数据库,在该步骤中,我们专注于实现对数据库的操作,也就是增删改查。
(demo是数据库表名)
查询数据项:String sql =“select * from demo”;
插入数据项:String sql=“INSERT INTO demo(USER,PASSWORD) VALUES (?,?)”;
更新数据项:String sql = “UPDATE demo set user=?,password=? where user =?”;
删除数据项:String sql = “DELETE FROM demo where user =?”;
2.4 得到statement对象
查询:
statement = connection.prepareStatement(sql);
插入:
statement =connection.prepareStatement(sql);
statement.setString(1,"xu");
statement.setInt(2,123);
statement.executeUpdate();
更新:
statement = connection.prepareStatement(sql);
statement.setString(1, "su");
statement.setInt(2, 1234);
statement.setString(3,"xu");
statement.executeUpdate();
删除:
statement = connection.prepareStatement(sql);
statement.setString(1, "su");
statement.executeUpdate();
2.5 得到结果集(查询专属)
resultSet = statement.executeQuery();
2.6 遍历结果集(同上)
while(resultSet.next()){
System.out.println(resultSet.getInt(1));
System.out.println(resultSet.getInt(2));
}
2.7 释放连接
数据库连接(Connection)非常耗资源,尽量晚创建,尽量早的释放,都要加try catch 以防前面关闭出错,后面的就不执行了。
public static void closeConnection(ResultSet resultSet,PreparedStatement statement,Connection connection){
if(resultSet!= null){
try {
resultSet.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(connection!= null){
try{
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(statement != null){
try{
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
2.8 结语
完成以上步骤,即可使用JDBC对数据库进行简单操作。