一、 JDBC
jdbc用于java与数据库之间的连接,是java提供的接口规范,由不同的数据库厂商实现这些接口编写的实现类称为驱动,以MySQL为例:(MySQL驱动)

二、在IDEA中使用JDBC建立与MySQL的连接
创建一个java项目

在目录下添加一个“libs”文件夹,并将驱动复制到该文件夹下,右键选定“add as library”

步骤一:加载驱动,版本5之后该步可以省略,在驱动的jar包下有:


已经会帮我们加载了,但是最好还是写上:
//1.加载驱动
Class.forName("com.mysql.jdbc.Driver");
步骤二:创建连接,user?问号前为连接的数据库名,user=“为数据库的用户名”,password = “数据库密码”
//2.创建连接
Connection connection = DriverManager.getConnection
("jdbc:mysql://127.0.0.1:3306/user?useSSL=true&" +
"characterEncoding=utf-8&user=" +
"root&password=root");
System.out.println("创建连接成功");
步骤三:定义一个SQL语句
//3.写sql
String sql="select * from userinfo";
步骤四:得到statement对象,用于执行sql语句
//4.得到statement对象
PreparedStatement statement = connection.prepareStatement(sql);
步骤五:执行sql语句获得结果集
//5.执行sql得到结果集
ResultSet rs = statement.executeQuery();
步骤六:处理结果集
//6.处理结果集
while (rs.next()){
System.out.println(rs.getInt(1));
System.out.println(rs.getString(2));
System.out.println(rs.getString(3));
}
步骤七:关闭资源,一般写在try catch的finally中
try {
....
} catch (Exception e) {
e.printStackTrace();
}finally{
DB.close(rs,statement,cnn);
}
其中close是将释放资源封装成一个方法:
public static void close(ResultSet rs,Statement statement,Connection cnn){
if(rs!=null){
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(statement!=null){
try {
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(cnn!=null){
try {
cnn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
三、测试


本文介绍了JDBC,它是Java与数据库连接的接口规范,不同数据库厂商实现接口的类为驱动。重点讲解了在IDEA中使用JDBC建立与MySQL连接的步骤,包括创建项目、添加驱动,以及加载驱动、创建连接、执行SQL语句等,最后还提到了测试。
3万+

被折叠的 条评论
为什么被折叠?



