JDBC連線MySQL和SQL Server的工具類
簡單的JDBC連線,沒有用c3p0之類的連線方式,所有連線資訊也直接放在了工具類裡,有需要的自己去改
JDBCUtils1.java
package mysqlutils;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import com.mysql.jdbc.Connection;
import com.mysql.jdbc.PreparedStatement;
public class JDBCUtils1 {
private static final String DBDRIVER = "com.mysql.jdbc.Driver";// 驅動類類名
private static final String DBNAME = "school";// 資料庫名
private static final String DBURL = "jdbc:mysql://localhost:3306/" + DBNAME;// 連線URL
private static final String DBUSER = "root";// 資料庫使用者名稱
private static final String DBPASSWORD = "tjw19951105" ;// 資料庫密碼
private static Connection conn = null;
private static PreparedStatement ps = null;
private static ResultSet rs = null;
/*
* 獲取資料庫連線
*/
public static Connection getConnection() {
try {
Class.forName(DBDRIVER);// 註冊驅動
conn = (Connection) DriverManager.getConnection(DBURL, DBUSER,
DBPASSWORD);// 獲得連線物件
System.out.println("成功載入MYSQL驅動程式");
} catch (ClassNotFoundException e) {// 捕獲驅動類無法找到異常
System.out.println("找不到MYSQL驅動程式");
System.out.println(e.toString());
e.printStackTrace();
} catch (SQLException e) {// 捕獲SQL異常
e.printStackTrace();
}
return conn;
}
public static ResultSet select(String sql) throws Exception {
try {
conn = getConnection();
ps = (PreparedStatement) conn.prepareStatement(sql);
rs = ps.executeQuery(sql);
return rs;
} catch (SQLException sqle) {
throw new SQLException("select data Exception: "
+ sqle.getMessage());
} catch (Exception e) {
throw new Exception("System error: " + e.getMessage());
}
}
/*
* 增刪改均呼叫這個方法
*/
public static void updata(String sql) throws Exception {
try {
conn = getConnection();
ps = (PreparedStatement) conn.prepareStatement(sql);
ps.executeUpdate();
} catch (SQLException sqle) {
throw new SQLException("insert data Exception: "
+ sqle.getMessage());
} finally {
try {
if (ps != null) {
ps.close();
}
} catch (Exception e) {
throw new Exception("ps close exception: " + e.getMessage());
}
try {
if (conn != null) {
conn.close();
}
} catch (Exception e) {
throw new Exception("conn close exception: " + e.getMessage());
}
}
}
}
JDBCUtils2.java
package sqlserverutils;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class JDBCUtils2 {
private static final String DBDRIVER = "com.microsoft.sqlserver.jdbc.SQLServerDriver";// 驅動類類名
private static final String DBNAME = "school";// 資料庫名
// jdbc:sqlserver://localhost:1433;DatabaseName=school","sa","tjw19951105"
private static final String DBURL = "jdbc:sqlserver://localhost:1433;DatabaseName="+DBNAME;// 連線URL
private static final String DBUSER = "sa";// 資料庫使用者名稱
private static final String DBPASSWORD = "tjw19951105";// 資料庫密碼
private static Connection conn = null;
private static PreparedStatement ps = null;
private static ResultSet rs = null;
/*
* 獲取資料庫連線
*/
public static Connection getConnection() {
try {
Class.forName(DBDRIVER);// 註冊驅動
conn = DriverManager.getConnection(DBURL,DBUSER,
DBPASSWORD);// 獲得連線物件
System.out.println("成功載入SQL Server驅動程式");
} catch (ClassNotFoundException e) {// 捕獲驅動類無法找到異常
System.out.println("找不到SQL Server驅動程式");
System.out.println(e.toString());
e.printStackTrace();
} catch (SQLException e) {// 捕獲SQL異常
e.printStackTrace();
}
return conn;
}
public static ResultSet select(String sql) throws Exception {
try {
conn = getConnection();
ps = (PreparedStatement) conn.prepareStatement(sql);
rs = ps.executeQuery();
return rs;
} catch (SQLException sqle) {
throw new SQLException("select data Exception: "
+ sqle.getMessage());
} catch (Exception e) {
throw new Exception("System error: " + e.getMessage());
}
}
/*
* 增刪改均呼叫這個方法
*/
public static void updata(String sql) throws Exception {
try {
conn = getConnection();
ps = (PreparedStatement) conn.prepareStatement(sql);
ps.executeUpdate();
} catch (SQLException sqle) {
throw new SQLException("insert data Exception: "
+ sqle.getMessage());
} finally {
try {
if (ps != null) {
ps.close();
}
} catch (Exception e) {
throw new Exception("ps close exception: " + e.getMessage());
}
try {
if (conn != null) {
conn.close();
}
} catch (Exception e) {
throw new Exception("conn close exception: " + e.getMessage());
}
}
}
}
Student.java
package domain;
public class Student {
int sno;
String sname;
int sage;
String ssex;
public Student(int sno, String sname, int sage, String ssex) {
super();
this.sno = sno;
this.sname = sname;
this.sage = sage;
this.ssex = ssex;
}
public int getSno() {
return sno;
}
public void setSno(int sno) {
this.sno = sno;
}
public String getSname() {
return sname;
}
public void setSname(String sname) {
this.sname = sname;
}
public int getSage() {
return sage;
}
public void setSage(int sage) {
this.sage = sage;
}
public String getSsex() {
return ssex;
}
public void setSsex(String ssex) {
this.ssex = ssex;
}
@Override
public String toString() {
return "Student [sno=" + sno + ", sname=" + sname + ", sage=" + sage
+ ", ssex=" + ssex + "]";
}
}
Test.java
package MainClass;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
import domain.Student;
import mysqlutils.JDBCUtils1;
/**
* 1.插入刪除修改寫法其實都是一樣的,唯一的區別在於SQL語句不同,直接替換相應的SQL語句就行了,下邊我分開寫是為了看的更清楚
* 2.用之前只需要去JDBCUtils1中修改DBNAME、DBPASSWORD就好,如果不是root使用者則順帶改了DBUSER
* 3.查詢的呼叫方法:ResultSet rs = JDBCUtils1.select(sql);
* 4.增刪改查呼叫的方法:JDBCUtils1.updata(sql);
* 5.注意把我libs包下的jar包匯入並新增到path中
* 6.如果需要使用萬用字元,參考課本339頁Example11_5.java,這裡JDBCUtils1.getConnection()獲取連線以後,自己往下寫幾行程式碼就出來了
* 有問題就try——catch捕獲,這個不好封裝
* @author Lenovo_PC
*
*/
public class Test {
public static void main(String[] args) {
// TODO Auto-generated method stub
// selectData();//查詢資料
// insertData();//插入資料
// deleteData();//刪除資料
// updateDate();//修改資料
}
/**
* 修改資料
*/
private static void updateDate() {
System.out.println("修改MySQL資料庫資料");
String sql = "update student set sname = 'amy' where sname = 'tom'";
try {
JDBCUtils1.updata(sql);
System.out.println("修改成功!");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* 刪除資料
*/
private static void deleteData() {
System.out.println("刪除MySQL資料庫資料");
String sql = "delete from student where sname = 'tom'";
try {
JDBCUtils1.updata(sql);
System.out.println("刪除成功!");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* 插入資料
*/
private static void insertData() {
System.out.println("插入MySQL資料庫資料");
//這裡注意Sno,最好別重複,不過沒設定主鍵,重複也沒啥關係
String sql = "insert into student (sno, sname, sage, ssex) values (4, 'tom', 18, '女')";
try {
JDBCUtils1.updata(sql);
System.out.println("插入成功!");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* 查詢資料
*/
private static void selectData() {
System.out.println("查詢MySQL資料庫資料");
String sql = "select * from student";
List<Student> list = new ArrayList<Student>();
try {
ResultSet rs = JDBCUtils1.select(sql);
while (rs.next()) {
list.add(new Student(rs.getInt("sno"), rs.getString("sname"), rs.getInt("sage"), rs.getString("ssex")));
}
for (int i = 0; i < list.size(); i++) {
System.out.println(list.get(i));
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Test2.java
package MainClass;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
import mysqlutils.JDBCUtils1;
import sqlserverutils.JDBCUtils2;
import domain.Student;
/**
* 測試SQL Server的類,直接複製的Test
* 就是把JDBCUtils1改為JDBCUtils2
* @author Lenovo_PC
*
*/
public class Test2 {
public static void main(String[] args) {
// TODO Auto-generated method stub
// selectData();//查詢資料
// insertData();//插入資料
// deleteData();//刪除資料
// updateDate();//修改資料
}
/**
* 修改資料
*/
private static void updateDate() {
System.out.println("修改SQL Server資料庫資料");
String sql = "update student set sname = 'amy' where sname = 'tom'";
try {
JDBCUtils2.updata(sql);
System.out.println("修改成功!");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* 刪除資料
*/
private static void deleteData() {
System.out.println("刪除SQL Server資料庫資料");
String sql = "delete from student where sname = 'tom'";
try {
JDBCUtils2.updata(sql);
System.out.println("刪除成功!");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* 插入資料
*/
private static void insertData() {
System.out.println("插入SQL Server資料庫資料");
//這裡注意Sno,最好別重複,不過沒設定主鍵,重複也沒啥關係
String sql = "insert into student (sno, sname, sage, ssex) values (4, 'tom', 18, '女')";
try {
JDBCUtils2.updata(sql);
System.out.println("插入成功!");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* 查詢資料
*/
private static void selectData() {
System.out.println("查詢SQL Server資料庫資料");
String sql = "select * from student";
List<Student> list = new ArrayList<Student>();
try {
ResultSet rs = JDBCUtils2.select(sql);
while (rs.next()) {
list.add(new Student(rs.getInt("sno"), rs.getString("sname"), rs.getInt("sage"), rs.getString("ssex")));
}
for (int i = 0; i < list.size(); i++) {
System.out.println(list.get(i));
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
注意!!
SQL Server資料庫連線的時候可能會報錯,報錯情況如下:
文字描述:
com.microsoft.sqlserver.jdbc.SQLServerException: The TCP/IP connection to the host localhost, port 1433 has failed. Error: Connection refused: connect. Please verify the connection properties and check that a SQL Server instance is running on the host and accepting TCP/IP connections at the port, and that no firewall is blocking TCP connections to the port.
解決的辦法:TCP/IP協議給禁止了。點選“SQL Server Configuration Manager” -> “SQL Server XXX Network Configuration -> Protocols for MSSQL SERVER -> TCP/IP,如果是被禁止了,就啟動一下
這兒的話最近碰上個操蛋的問題,就是開啟了這個TCP/IP後還是報上邊的錯誤,找了半天是埠的問題,你的電腦可能是用的動態埠,而不是指定的1433,解決的辦法截圖在下邊了,自己照著做吧,打字太累了
還有就是更改完配置最好重啟一下服務,兩個辦法,一是去工作管理員自己找到相應服務結束了,而是通過這個配製管理器
再說一下SQL Server附加資料庫的問題
在sql 2008 R2附加資料庫的時候出現如下的錯誤:無法開啟物理檔案 “H:\LittleRan\SQL\SHOOL\Example.mdf”。作業系統錯誤 5:”5(拒絕訪問。)”。 (Microsoft SQL Server,錯誤: 5120)
解決辦法就是新增Everyone使用者,然後給它許可權,資料庫和日誌檔案都要改,這裡不截圖了,給個相關連結自己跳轉過去看吧
https://jingyan.baidu.com/article/c275f6ba2f7d41e33d75678d.html
下邊在提供一個不錯的工具類,與上個相比的話使用prepareStatement可以防止SQL注入,並且可以攜帶引數,另外資料庫連結部分的資訊是通過外部.properties檔案獲取的,後期修改只針對.properties檔案即可
JdbcUtil類:
package com.imooc.page.util;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
public class JDBCUtil {
private static String USERNAME;
private static String PASSWORD;
private static String DRIVER;
private static String URL;
private Connection connection;
private PreparedStatement pstmt;
private ResultSet resultSet;
static{
loadConfig();
}
/**
* 載入資料庫配置資訊,並給相關的屬性賦值
*/
public static void loadConfig(){
try {
InputStream inStream = JDBCUtil.class
.getResourceAsStream("/jdbc.properties");
Properties prop = new Properties();
prop.load(inStream);
USERNAME = prop.getProperty("jdbc.username");
PASSWORD = prop.getProperty("jdbc.password");
DRIVER = prop.getProperty("jdbc.driver");
URL = prop.getProperty("jdbc.url");
} catch (Exception e) {
throw new RuntimeException("讀取資料庫配置檔案異常!", e);
}
}
public JDBCUtil() {
}
public Connection getConnection() {
try {
Class.forName(DRIVER);
connection = DriverManager.getConnection(URL, USERNAME, PASSWORD);
} catch (Exception e) {
throw new RuntimeException("get connection error!");
}
return connection;
}
/**
* 執行更新操作
* @param sql sql語句
* @param params 執行引數
* @return 執行結果
* @throws SQLException
*/
public boolean updateByPreparedStatement(String sql, List<?> params)
throws SQLException {
boolean flag = false;
int result = -1;// 表示當用戶執行新增刪除和修改的時候所影響資料庫的行數
pstmt = connection.prepareStatement(sql);
int index = 1;
// 填充sql語句中的佔位符
if (params != null && !params.isEmpty()) {
for (int i = 0; i < params.size(); i++) {
pstmt.setObject(index++, params.get(i));
}
}
result = pstmt.executeUpdate();
flag = result > 0 ? true : false;
return flag;
}
/**
* 執行查詢操作
* @param sql sql語句
* @param params 執行引數
* @return
* @throws SQLException
*/
public List<Map<String, Object>> findResult(String sql, List<?> params)
throws SQLException {
List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
int index = 1;
pstmt = connection.prepareStatement(sql);
if (params != null && !params.isEmpty()) {
for (int i = 0; i < params.size(); i++) {
pstmt.setObject(index++, params.get(i));
}
}
resultSet = pstmt.executeQuery();
ResultSetMetaData metaData = resultSet.getMetaData();
int cols_len = metaData.getColumnCount();
while (resultSet.next()) {
Map<String, Object> map = new HashMap<String, Object>();
for (int i = 0; i < cols_len; i++) {
String cols_name = metaData.getColumnName(i + 1);
Object cols_value = resultSet.getObject(cols_name);
if (cols_value == null) {
cols_value = "";
}
map.put(cols_name, cols_value);
}
list.add(map);
}
return list;
}
/**
* 釋放資源
*/
public void releaseConn() {
if (resultSet != null) {
try {
resultSet.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (pstmt != null) {
try {
pstmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
.properties檔案:
jdbc.username = root
jdbc.password = **your password**
jdbc.driver = com.mysql.jdbc.Driver
jdbc.url = jdbc:mysql://localhost:3306/dividepage