JAVA 学习日记(4).JDBC

时间:2022-09-21 15:39:22

JDBC连接数据库

DBUtil.java
package com.zrgj.shanji.util;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import com.mysql.jdbc.ResultSet;


// 导包

// 加载驱动com.mysql.jdbc.Driver
public class DBUtil {
public DBUtil(){
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// 创建连接对象Connection
public Connection getConn(){
Connection conn=null;
try {
conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/student?useUnicode=true&characterEncoding=UTF-8", "root", "root");
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return conn;
}

public int add_delete_update(String sql, Object...obj){
Connection conn=null;
// PreparedStatement是创建SQL语句的命令
PreparedStatement pstmt=null;
int result=0;
conn=getConn();
try {
// 获取连接数据库的执行sql语句对象
pstmt=conn.prepareStatement(sql);
if (obj.length>0) {
for (int i = 0; i < obj.length; i++) {
// i+1是sql语句问号处理,下标从1开始,obj[i]是具体参数值
pstmt.setObject((i+1), obj[i]);
}
}
// executeUpdate执行sql语句
result=pstmt.executeUpdate();
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
return result;
}

public static void closeAll(ResultSet rs,PreparedStatement pstmt,Connection conn){
try {
if (rs!=null) {
rs.close();
}

if(pstmt!=null){
pstmt.close();
}

if (conn!=null) {
conn.close();
}

}catch (SQLException e) {
e.printStackTrace();
}
}


public static void main(String[] args) {
DBUtil db=new DBUtil();
Connection conn=db.getConn();
if(conn!=null){
System.out.println("连接成功!");
// int rs=db.add_delete_update(sql, null);
// System.out.println(rs);
}
}
}