導航:首頁 > 編程語言 > 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相關的資料

熱點內容
抖音喜歡加密了怎麼打開 瀏覽:385
mysql命令行顯示表 瀏覽:364
國防離我們源碼200字 瀏覽:777
vmwaretoolslinux 瀏覽:92
命令方塊生存放不了嗎 瀏覽:697
程序員入門很難嗎 瀏覽:102
70後程序員照片 瀏覽:192
一個普通程序員能幹多久 瀏覽:936
adobe的PDF轉換器 瀏覽:862
單片機數字碼表匯編 瀏覽:486
單片機開發用的軟體 瀏覽:159
程序員8個演算法題 瀏覽:402
php題庫系統 瀏覽:228
王牌戰爭文明重啟選什麼伺服器 瀏覽:662
簡述對稱加密法 瀏覽:665
c語言數學編程 瀏覽:998
F1B命令 瀏覽:630
cs命令快捷鍵 瀏覽:852
阿里雲購買伺服器如何用現金支付 瀏覽:698
pythontime等待 瀏覽:996