JDBC
数据库连接的步骤
第一步:注册驱动
第二步:获取连接
第三步:获取statement对象
第四步:执行SQL语句返回结果集
第五步:遍历结果集
第六步:关闭连接释放资源
编译时不依赖的数据库连接代码
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class JDBCDemo {
private static final String url = "jdbc:mysql://localhost:3306/demo?serverTimezone=GMT%2B8";
private static final String user = "root";
private static final String password = "362522";
static Connection connection = null;
static Statement stmt = null;
static ResultSet rs1 = null;
public static void update(){ //增、删、改
try {
Class.forName("com.mysql.cj.jdbc.Driver");
// a、加载具体的驱动类
//connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/demo?useSSL=false&serverTimezone=UTC","root","362522");
connection = DriverManager.getConnection(url, user, password);
//b、连接数据库
stmt = connection.createStatement();
//c、操作数据库
/*
String sql1 = "insert into student value('9','aud','68')";
int count = stmt.executeUpdate(sql1);//执行sql语句,增、删、改,返回执行结果
if (count > 0) {
System.out.println("操作成功!");
}
*/
String sql = "select * from student";
ResultSet rs1 = stmt.executeQuery(sql);
while (rs1.next()){
int sid = rs1.getInt("sid");
String name = rs1.getString("sname");
double score = rs1.getDouble("score");
System.out.println(sid+" "+name+" "+score);
}
} catch (ClassNotFoundException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
} catch (SQLException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}finally{
try {
if (rs1 !=null){
rs1.close();
}
if (stmt != null) {
stmt.close();
}
if (connection != null) {
connection.close();
}
} catch (SQLException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
}
}
public static void main(String[] args){
update();
}
}