java操作数据库步骤:
1.注册并加载驱动
DriverManager.registerDriver(Driver driver);
或者Class.forName("driverName");
注意:在开发中,通常使用Class.forName("com.mysql.jdbc.Driver");注册驱动,不用DriverManager.registerDriver(driver);因为这个方法注册了两次驱动。
2.获取Connection连接对象
Connection con = DriverManager.getConnection(url,username,password);
3.获取操作数据库的对象Statement(或者PreparedStatement)
Statement stmt = con.createStatement();
4.向数据库发送sql语句,执行操作。
比如:String sql = "select * from users";调用executeQuery(sql)
5.执行查询操作,返回ResultSet结果集对象,结果集里面封装的是查询的结果。
遍历ResultSet,获取我们查询的数据
6.关闭连接,释放资源(倒关原则,先出现的,后关闭)
Demo:
1.创建数据库::jdbc,在这个数据库里创建表,插入几条数据
create datebase ydd01;
use ydd01;
CREATE TABLE users (
id INT PRIMARY KEY auto_increment,
name VARCHAR ( 32 ),
password VARCHAR ( 32 ),
email VARCHAR ( 160 ),
birthday Date
);
insert into users(name,password,email,birthday) values('hh','123','hh@qq.com','1990-09-09');
insert into users(name,password,email,birthday) values('ydd','123','ydd@qq.com','1991-09-09');
insert into users(name,password,email,birthday) values('lyy','123','lyy@qq.com','1992-09-09');
insert into users(name,password,email,birthday) values('ljj','123','ljj@qq.com','1993-09-09');
2.操作代码
package cn.itcast.jdbc.example;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.management.RuntimeErrorException;
import java.sql.Date;
import com.mysql.jdbc.Driver;
public class Example01 {
// 执行查询操作
public static void main(String[] args) {
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
try {
// 1.注册并加载驱动
Driver driver = new Driver();
//DriverManager.registerDriver(driver);
Class.forName("com.mysql.jdbc.Driver");
// 2.获取连接对象
String url = "jdbc:mysql://localhost:3306/ydd01";
String user = "root";
String password = "123456";
con = DriverManager.getConnection(url, user, password);
// 3.获取操作数据的对象
stmt = con.createStatement();
// 4.向数据库发送查询语句
String sql01 = "select * from users";
rs = stmt.executeQuery(sql01);
// 5.获取查询的数据
while (rs.next()) {
int id = rs.getInt("id");
String name = rs.getString("name");
String password01 = rs.getString("password");
String email = rs.getString("email");
Date birthday = rs.getDate("birthday");
System.out.println(id + " " + name + " " + password01 + " " + email + " " + birthday);
}
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
// 6.关闭连接,释放资源
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (rs != null) {
try {
stmt.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (con != null) {
try {
con.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println("关闭资源代码已执行");
}
}
}
评论区