1.下载jar包
-
下载地址:mvnrepository
-
搜索jar包
-
下载对应的版本
2.导入包
项目的根目录下新建lib目录,将下载好的包复制进去,最后右击lib目录->Add as Library...
3.编写代码
package com.sanduo.lesson01;
import java.sql.*;
// 第一个jdbc程序
public class JdbcFirstDemo {
public static void main(String[] args) throws ClassNotFoundException, SQLException {
//1. 加载驱动
Class.forName("com.mysql.jdbc.Driver"); //反射实现
//2. 用户信息url
// useUnicode=true&characterEncoding=utf8&useSSL=true
String url = "jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8&useSSL=true";
String username = "root";
String password = "root";
//3. 连接成功,数据库对象 Connection 代表数据库
Connection connection = DriverManager.getConnection(url, username, password);
//4. 执行SQL的对象 Statement 执行SQL
Statement statement = connection.createStatement();
//5. 执行SQL的对象去执行SQL
String sql = "select * from `user`";
ResultSet resultSet = statement.executeQuery(sql);// 回返的结果集
if(!resultSet.next()){
System.out.println("暂无数据");
}
while (resultSet.next()){
System.out.println("id="+resultSet.getObject("id"));
System.out.println("name="+resultSet.getObject("name"));
System.out.println("age="+resultSet.getObject("age"));
System.out.println("password="+resultSet.getObject("password"));
}
//6. 释放连接
resultSet.close();
statement.close();
connection.close();
}
}