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

熱點內容
編程珠璣筆記 瀏覽:276
結束命令行 瀏覽:268
力學原理pdf 瀏覽:731
宏定義編譯後不變 瀏覽:399
如何搞免費伺服器 瀏覽:208
神經系統pdf 瀏覽:667
如何查看伺服器上的資料庫伺服器 瀏覽:190
壓縮機型號v代表什麼 瀏覽:54
旅遊類源碼 瀏覽:864
電腦伺服器類型怎麼設置 瀏覽:232
pdf炒股 瀏覽:788
伺服器地址缺少埠號什麼意思 瀏覽:532
下載需要解壓的小說用哪個軟體 瀏覽:536
廣東分布式伺服器雲主機 瀏覽:585
伺服器忙打不開怎麼辦 瀏覽:17
tif壓縮軟體 瀏覽:415
程序員那麼可愛陸漓上班第1天 瀏覽:952
macbookair自帶什麼app 瀏覽:703
如何關了加密的軟體 瀏覽:583
程序員p2p待遇 瀏覽:923