導航:首頁 > 編程語言 > java訪問mysql

java訪問mysql

發布時間:2025-03-09 00:40:51

A. java怎樣連接mysql資料庫

1、java連接MySQL資料庫需要有一個驅動jar包

例如:mysql-connector-java-5.1.26-bin.jar,

package.test.jsp;
importjava.sql.Connection;
importjava.sql.DriverManager;
importjava.sql.ResultSet;
importjava.sql.SQLException;
importjava.sql.Statement;

importjavax.naming.spi.DirStateFactory.Result;

publicclassDbConnection{
privatestaticConnectionconn;
publicDbConnection(){
Stringdrivername="com.mysql.jdbc.Driver";
Stringusername="root";
Stringurl="jdbc:mysql://localhost/jsptest?useUnicode=true&characterEncoding=UTF-8";
Stringpassword="";
//載入驅動
try{
Class.forName(drivername);
}catch(ClassNotFoundExceptione){
System.out.println("驅動載入失敗!");
e.printStackTrace();
}
//建立連接
try{
conn=DriverManager.getConnection(url,username,password);
}catch(SQLExceptione){
System.out.println("資料庫連接失敗!");
e.printStackTrace();
}


}
//getResultSet
publicResultSetGetResultSet(Stringsql)
{
ResultSetrs=null;
//statemanage
try{
Statementst=conn.createStatement();
rs=st.executeQuery(sql);
}catch(SQLExceptione){
System.out.println("狀態管理器創建失敗");
e.printStackTrace();
}
returnrs;

}
//DML
publicintDML(Stringsql)
{
intcount=-1;
try{
Statementstatement=conn.createStatement();
count=statement.executeUpdate(sql);
}catch(SQLExceptione){
System.out.println("狀態管理器創建失敗");
e.printStackTrace();
}
returncount;
}
}

3、可以新建service類來調用連接類裡面的getResultSet方法和DML,實現自己所需用的功能。

閱讀全文

與java訪問mysql相關的資料

熱點內容
肌肉塑造全書pdf下載 瀏覽:796
安卓簡約拼圖用什麼軟體好 瀏覽:289
fx1n加密程序 瀏覽:844
淘客阿里雲伺服器 瀏覽:476
100壓縮打造 瀏覽:422
安卓手機怎麼和蘋果平板傳文件 瀏覽:973
開始選項卡中的頁眉和頁腳命令選項 瀏覽:424
pdf的字體怎麼改 瀏覽:856
python讀寫視頻 瀏覽:88
科魯茲壓縮機軸承 瀏覽:353
word文檔轉換成pdf文件找不到 瀏覽:27
組件注冊命令 瀏覽:760
安卓大屏導航用的是什麼運放 瀏覽:443
myandroidtools的備份 瀏覽:900
python爬蟲天氣預報 瀏覽:761
android70許可權管理 瀏覽:749
魔獸辛迪加是什麼伺服器 瀏覽:472
電腦文件夾排序怎麼自定義排序 瀏覽:41
android70機型 瀏覽:422
阿里程序員地位 瀏覽:183