目录
- 加载驱动
- 获取连接
- 创建会话
- 发送SQL
- 处理结果
- 关闭资源
- 测试
加载驱动
Class.forName("com.mysql.cj.jdbc.Driver");
获取连接
String url = "jdbc:mysql://127.0.0.1:3306/book";
String username = "root" ;
String password = "root" ;
Connection conn = DriverManager.getConnection(url,username,password);
创建会话
Statement sta = conn.createStatement();
发送SQL
ResultSet res = sta.executeQuery("select * from t_book");
处理结果
while (res.next()){
System.out.println(res.getInt("id") + "--" + res.getString("name") + "--" + res.getString("author") + "--" + res.getDouble("price"));
}
关闭资源
sta.close();
conn.close();
测试
import java.sql.*;
public class Test01 {
public static void main(String[] args) throws ClassNotFoundException, SQLException {
Class.forName("com.mysql.cj.jdbc.Driver");
String url = "jdbc:mysql://127.0.0.1:3306/book";
String username = "root" ;
String password = "root" ;
Connection conn = DriverManager.getConnection(url,username,password);
Statement sta = conn.createStatement();
ResultSet res = sta.executeQuery("select * from t_book");
while (res.next()){
System.out.println(res.getInt("id") + "--" + res.getString("name") + "--" + res.getString("author") + "--" + res.getDouble("price"));
}
sta.close();
conn.close();
}
}