java程序连接数据库
先导入数据库驱动包mysql-connector-java-8.0.15.jar
配置好环境后,建一个class
下面开始操作
1.加载并注册数据库驱动
Class.forName("com.mysql.cj.jdbc.Driver");
2.通过DriverManager获取数据库连接
Mysql5.6及5.6之后的版本都要写上serverTimezone=GMT%2B8"
String url = "jdbc:mysql://localhost:3306/test?serverTimezone=GMT%2B8"; String username = "root"; String password = "123"; conn = DriverManager.getConnection(url, username, password);
3.通过Connection对象获取Statement对象
stmt = conn.createStatement();
4.使用statement对象执行SQL语句
String sql = "select * from users"; rs = stmt.executeQuery(sql);
5.操作ResultSet结果集
while (rs.next()){
int id = rs.getInt("id");
String name = rs.getString("name");
System.out.println(id+name);
}
6.关闭连接,释放资源(倒着关)
现在写一个完整的JDBC程序package com.jingjing;
import java.sql.*;
public class Ex01 {
public static void main(String[] args) {
ResultSet rs = null;
Statement stmt = null;
Connection conn = null;
try {
Class.forName("com.mysql.cj.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/test?serverTimezone=GMT%2B8";
String username = "root";
String password = "123";
conn = DriverManager.getConnection(url, username, password);
stmt = conn.createStatement();
String sql = "select * from users";
rs = stmt.executeQuery(sql);
while (rs.next()){
int id = rs.getInt("id");
String name = rs.getString("name");
System.out.println(id+name);
}
} catch (Exception e) {
e.printStackTrace();
}finally {
if(rs!=null){
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(stmt!=null){
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(conn!=null){
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
}



