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,實現自己所需用的功能。