Java連接mysql數據庫的兩種途徑:JDBC和連接池
2016.09.25 13:27
8112瀏覽
永遠懷著一顆卑微的心
- 使用JDBC連接數據庫
BaseDao類
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;
public class BaseDao {
Connection conn = null;
public Connection getConnection() { //連接方法
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/數據庫名", "root", "數據庫密碼");
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return conn;
}
public void CloseAll(Connection conn, Statement st, ResultSet rs) { //關閉方法
try {
if (rs != null) {
rs.close();
}
if (st != null) {
st.close();
}
if (conn != null) {
conn.close();
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public int ExceuteUpdate(String sql,Object...prams){ //增刪改建議套用方法
int result = 0;
conn = getConnection();
try {
pstmt = conn.prepareStatement(sql);
if(prams != null){
for(int i =0;i<prams.length;i++){
pstmt.setObject(i+1, prams[i]);
}
}
result = pstmt.executeUpdate();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally{
closeAll(conn,pstmt,rs);
}
return result;
}
}
- 使用連接池連接數據庫
首先在一下apache中的conf文件夾中的context.xml文件添加下面這段配置信息
<Resource
name="jdbc/message"
auth="Container"
type="javax.sql.DataSource"
maxActive = "100"
maxIdle="30" maxWait="10000" username="root" password="123456"
driverClassName = "com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost:3306/message"
/>
可將上面的配置信息直接在項目中創建一個context.xml文件將信息復制進去
當然也可在項目中的web.xml中寫入配置信息(二者選其一)
<resource-ref>
<description>news DateSource</description>
<res-ref-name>jdbc/message</res-ref-name>
<res-type>javax.sql.DateSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
在BaseDao中的連接方法如下
public Connection getConnection(){
Context ctx = null;
try {
ctx = new InitialContext();//初始化上下文
DataSource ds= (DataSource)ctx.lookup("java:comp/env/jdbc/message");//date對象
conn = ds.getConnection();
} catch (NamingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return conn;
}
記得添加mysql的jar包,這點很重要!
生活就像代碼,恰逢其會,猝不及防,學著去做一些有意義的事情,做自己想做的事。
點擊查看更多內容
7人點贊
評論
共同學習,寫下你的評論
評論加載中...
相關文章推薦
正在加載中
慕課專欄
更多