JDBC操作步骤
使用步骤
JDBC连接步骤
JDBC执行SQL语句
一旦获得了连接,我们可以与数据库进行交互。JDBC Statement和PreparedStatement接口定义了使您能够发送SQL命令并从数据库接收数据的方法和属性。
Statement
查看数据库中的数据:
package com;
import java.sql.*;
public class Demo01 {
public static void main(String[] args) {
Connection connection = null;
Statement statement = null;
ResultSet resultSet = null;
try {
//1.加载驱动
Class.forName("com.mysql.cj.jdbc.Driver");//com在src里
//2.获取链接
String useName = "root";
String passWard = "123456";
String url = "jdbc:mysql://localhost:3306/mysql01?serverTimezone=UTC";//mysql01是数据库名
connection = DriverManager.getConnection(url, useName, passWard);
//3.定义SQL,创建状态通道(进行SQL语句的发送)
statement = connection.createStatement();
resultSet = statement.executeQuery("select * from student");//executeQuery(sql)执行查询语句
//4.取出结果集信息
while (resultSet.next()){
//resuleSet.getxxx(列名);//xxx是数据类型
System.out.println(resultSet.getString("address")+" "+resultSet.getString("stuname"));
}
} catch (SQLException throwables) {
throwables.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} finally {
try {
if (connection != null) {
connection.close();
}
if (statement != null) {
statement.close();
}
if (resultSet != null) {
resultSet.close();
}
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
}
增删改数据库中的数据:
package com;
import java.sql.*;
public class Demo01 {
public static void main(String[] args) {
Connection connection = null;
Statement statement = null;
try {
//1.加载驱动
Class.forName("com.mysql.cj.jdbc.Driver");
//2.获取链接
String useName = "root";
String passWard = "123456";
String url = "jdbc:mysql://localhost:3306/mysql01?serverTimezone=UTC";
connection = DriverManager.getConnection(url, useName, passWard);
//3.定义SQL,创建状态通道(进行SQL语句的发送)
statement = connection.createStatement();
int result = statement.executeUpdate("insert into dept1(deptno,dname,loc) values(50,'哈哈','呵呵')");//executeQuery(sql)执行查询语句
//4.取出结果集信息
if (result > 0){
System.out.println("修改成功");
}else {
System.out.println("修改失败");
}
} catch (SQLException throwables) {
throwables.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} finally {
try {
if (connection != null) {//connection.notnull
connection.close();
}
if (statement != null) {
statement.close();
}
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
}