使用方法:
1.在項目的resources文件里添加data.properties文件,內(nèi)容為
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/數(shù)據(jù)庫名?characterEncoding=utf-8
user=用戶名
password=密碼
2.項目采取單例模式,getStatement方法獲取查詢sql操作對象
3.getPreparedStatement方法獲取增刪改操作對象,預(yù)操作防止sql注入
4.使用完之后建議調(diào)用closeConnection方法關(guān)閉鏈接。
//
// Created by bianys on 2022/12/20.
// author: bianys
//
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.sql.*;
import java.util.Properties;
public class JdbcUtil {private static Connection conn = null;
private static Statement stmt = null;
private static ResultSet rs = null;
private static PreparedStatement ps = null;
private static Properties p = new Properties();
private static FileInputStream fis= null;
//單例模式
static {try {Path path = Paths.get("src/main/resources/data.properties");
fis = new FileInputStream(path.toAbsolutePath().toString());
} catch (FileNotFoundException e) {e.printStackTrace();
}
try {p.load(fis);
} catch (IOException e) {e.printStackTrace();
}
String driver=p.getProperty("driver");
String user=p.getProperty("user");
String url=p.getProperty("url");
String password=p.getProperty("password");
//1.注冊驅(qū)動
//DriverManager.registerDriver(new com.mysql.jdbc.Driver());
try {Class.forName(driver);
//2.獲取連接
conn= DriverManager.getConnection(url,user,password);
} catch (ClassNotFoundException | SQLException e) {e.printStackTrace();
}
}
public static Statement getStatement(){try
{//3.創(chuàng)建數(shù)據(jù)庫操作對象
return conn.createStatement();
}catch (SQLException e){e.printStackTrace();
}
return null;
}
public static PreparedStatement getPreparedStatement(String sql){try
{//3.創(chuàng)建數(shù)據(jù)庫操作對象
return conn.prepareStatement(sql);
}catch (SQLException e){e.printStackTrace();
}
return null;
}
public static void closeConnection(){if (stmt!=null)
{try
{stmt.close();
}
catch (SQLException e)
{e.printStackTrace();
}
}
if (ps!=null)
{try
{ps.close();
}
catch (SQLException e)
{e.printStackTrace();
}
}
if (conn!=null)
{try
{conn.close();
}
catch (SQLException e)
{e.printStackTrace();
}
}
if (rs!=null)
{try
{rs.close();
}
catch (SQLException e)
{e.printStackTrace();
}
}
}
}
你是否還在尋找穩(wěn)定的海外服務(wù)器提供商?創(chuàng)新互聯(lián)www.cdcxhl.cn海外機房具備T級流量清洗系統(tǒng)配攻擊溯源,準確流量調(diào)度確保服務(wù)器高可用性,企業(yè)級服務(wù)器適合批量采購,新人活動首月15元起,快前往官網(wǎng)查看詳情吧
當前標題:jdbc使用模板-創(chuàng)新互聯(lián)
當前鏈接:http://jinyejixie.com/article46/digheg.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供ChatGPT、定制開發(fā)、品牌網(wǎng)站設(shè)計、品牌網(wǎng)站制作、自適應(yīng)網(wǎng)站、關(guān)鍵詞優(yōu)化
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)
猜你還喜歡下面的內(nèi)容