通讯录和数据库(MYSQL)相连
package com.softeem.jps;import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
public class DBConnection {
/** driver name */
private static String driverName = "";
/** url name */
private static String url = "";
/** user name */
private static String userName = "";
/** user password */
private static String userPass = "";
/**
* 不能创建实例
*/
private DBConnection() {
}
/**
* 跟据用户名,密码得到数据库连接
*
* @param _userName
* @param _userPass
* @return
* @throws ClassNotFoundException
* @throws SQLException
*/
public static Connection getConnection(String _userName, String _userPass)
throws ClassNotFoundException, SQLException {
// mysql
driverName = "com.mysql.jdbc.Driver";
url = "jdbc:mysql://127.0.0.1:3306/db_user?characterEncoding=gbk";
// sql server 2005
// driverName = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
// url = "jdbc:sqlserver://127.0.0.1:1433;database=mytest";
// oracle
// driverName = "oracle.jdbc.driver.OracleDriver";
// url = "jdbc:oracle:thin:@127.0.0.1:1521:orcl";
userName = _userName;
userPass = _userPass;
Connection conn = null;
Class.forName(driverName);
conn = DriverManager.getConnection(url, userName, userPass);
return conn;
}
/**
* 得到数据库连接
*
* @return
* @throws ClassNotFoundException
* @throws SQLException
*/
public static Connection getConnection() throws ClassNotFoundException,
SQLException {
return getConnection("root","19880629");
}
/**
* 关闭数据库连接
*
* @param conn
*/
public static void closeConnection(Connection conn) {
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
public static List executeQuery(String sql) {
List list = new ArrayList();
// jdbc...
return list;
}
public static int executeUpdate(String sql) {
int result = -1;
// jdbc...
return result;
}
/**
* 测试及使用示例
*
* @param args
*/
public static void main(String[] args) {
Connection conn = null;
try {
conn = getConnection("root", "19880629");
System.out.println(conn);
} catch (Exception e) {
e.printStackTrace();
}
closeConnection(conn);
}
}