1、直接上代码
分为:加载驱动块、创建连接块、关闭源块
package com.test;
import java.sql.*;
public class jdbcUtil {
Connection con;
Statement statement;
ResultSet res;
private static String DRIVE="com.mysql.jdbc.Driver";
private static String URL;
private static String NAME;
private static String PWD;
static {
try {
//加载驱动
// DRIVE="com.mysql.jdbc.Driver";
Class.forName(DRIVE);
URL="jdbc:mysql://localhost:3306/website?useUnicode=true&characterEncoding=utf8&useSSL=false";
NAME="root";
PWD="123456";
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
//创建连接
public static Connection getConnection() throws SQLException {
return DriverManager.getConnection(URL,NAME,PWD);
}
//关闭资源
public static void closeAll(Connection con,PreparedStatement pre,ResultSet res){
if(con!=null){
try {
con.close();
} catch (SQLException e) {
e.printStackTrace();
}finally {
con=null;
}
}
if(pre!=null){
try {
pre.close();
} catch (SQLException e) {
e.printStackTrace();
}finally {
pre=null;
}
}
if(res!=null){
try {
res.close();
} catch (SQLException e) {
e.printStackTrace();
}finally {
res=null;
}
}
}
}
2、测试使用
package com.test;
import org.junit.Test;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Scanner;
public class testjdbc {
Connection con;
PreparedStatement pre;
ResultSet res;
@Test
//查询
public void testSelect(){
try {
//获取连接
con= jdbcUtil.getConnection();
pre=con.prepareStatement("select * from user where id=?;");
pre.setString(1,"02");
res = pre.executeQuery();
while(res.next()){
System.out.println(res.getString(1));
System.out.println(res.getString(2));
}
jdbcUtil.closeAll(con,pre,res);
} catch (SQLException e) {
e.printStackTrace();
}
}
@Test
//插入操作
public void testInsert(){
//获取连接
try {
//获取连接
con=jdbcUtil.getConnection();
String sql="insert into user(id,name) values(?,?);";
pre=con.prepareStatement(sql);
pre.setString(1,"05");
pre.setString(2,"666");
int i = pre.executeUpdate();
System.out.println(i);
} catch (SQLException e) {
e.printStackTrace();
}
}
@Test
//更改操作
public void testUpdate(){
//获取连接
try {
con=jdbcUtil.getConnection();
String sql="update user set name='我的名' where id=?";
pre=con.prepareStatement(sql);
pre.setString(1,"05");
int i = pre.executeUpdate();
System.out.println(i);
jdbcUtil.closeAll(con,pre,res);
} catch (SQLException e) {
e.printStackTrace();
}
}
@Test
//删除操作
public void testDelete(){
try {
con=jdbcUtil.getConnection();
String sql="delete from user where id=?";
pre=con.prepareStatement(sql);
pre.setString(1,"02");
int i = pre.executeUpdate();
System.out.println(i);
} catch (SQLException e) {
e.printStackTrace();
}
}
}
注:@Test这个注解是测试用的,可以在代码中直接运行那个方法,相当于main
需要的依赖是:
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.10</version>
</dependency>