这周学习了Java连接数据库操作,数据库对于我们编程人员来说是非常重要的,以前学过MySQL,但一直没有学习Java如何连接数据库,这周才找到时间,学了一下
总的来说一共分为六个步骤
1.注册驱动
2.获取数据库连接
3.获取数据库操作对象
4.编写SQL语句
5处理查询结果集
6.关闭资源
import com.mysql.jdbc.Driver;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
public class Test01 {
public static void main(String[] args){
long start = System.currentTimeMillis();
//1.注册驱动
Connection conn = null;
Statement statement = null;
try {
Driver driver = new Driver();
DriverManager.registerDriver(driver);
//2.获取数据库连接
String url = "jdbc:mysql://localhost:3306/teacher";
String user= "root";
String password = "********";
conn = DriverManager.getConnection(url, user, password);
//3.获取数据库操作对象
statement = conn.createStatement();
//4.执行SQL语句
// String update = "update student set name='张六' where no=8";
// String insert = "insert into student(name) values('赵六')";
String delete = "delete from student where no = 8";
int count = statement.executeUpdate(delete);
System.out.println(count);
//5.处理查询结果集 (这里没有)
} catch (SQLException e) {
e.printStackTrace();
}finally{
//6.关闭资源
if(statement != null){
try {
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(conn != null){
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
long end = System.currentTimeMillis();
System.out.println(end - start);
}
}
当然如果写的多了,就感觉这样写很麻烦很浪费时间,这里其实可以对代码进行一些简单的封装,形成一个工具类,这样来的话就简单多了 ,这是我看视频,封装的工具类
import java.sql.*;
public class Test03 {
static{
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
public static Connection start() throws Exception{
String url = "jdbc:mysql://localhost:3306/teacher";
String user = "root";
String password = "*******";
Connection conn = DriverManager.getConnection(url, user, password);
return conn;
}
public static void close(Connection conn, Statement sta, ResultSet res){
if(res != null){
try {
res.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(sta != null){
try {
sta.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(conn != null){
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
当然对于和我这样的新手来说还是不用封装的工具类较好,多敲几遍原生代码,可能会记得更清晰,当然,如果是大神,那肯定还会有更好的封装办法。