1. 程式人生 > >小型Java Web專案之DatabaseConnection

小型Java Web專案之DatabaseConnection

做JavaWeb專案必然離不開資料庫,這裡使用的是MySQL資料庫進行開發。具體連結類如下:

package dbc;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.*;


public class DatabaseConnection
{
private static final String driver = "com.mysql.jdbc.Driver"; private static final String url = "jdbc:mysql://localhost:3306/myproject?characterEncoding=utf8&useSSL=true"; private static final String user = "**"; //這裡寫上使用者名稱 private static final String password = "**"; //這裡寫上密碼
private Connection conn = null; public DatabaseConnection() throws SQLException{ try { Class.forName(driver); this.conn = DriverManager.getConnection(url, user, password); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block
e.printStackTrace(); } } public Connection getConn() { return this.conn; } public void close(){ if(this.conn != null){ try { this.conn.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }

資料庫的連線還是比較容易的,但也應該很熟練。