JSP连接数据库代码
package com.examSystem.DBConnection;
import java.sql.*;
public class ConnectionDB {
//单态只能实例化自己
private static ConnectionDB connDB = new ConnectionDB();
//声明一个数据库连接
System.out.println("加载数据库驱动成功!" + dbdriver);
} catch (Exception e) {
System.err.println("加载数据驱动失败!具体信息:" + dbdriver);
}
//连接数据库
try {
conn = DriverManager.getConnection(URL, username, password);
//连接数据库用户名
private String username = "root";
//连接数据库密码
private String password = "root";
//私有的构造方法
private ConnectionDB() {
//加载数据库驱动
try {
Class.forName(dbdriver);
System.err.println("连接数据库url地址:" + URL);
System.err.println("连接数据库的用户名:" + username);
System.err.println("连接数据库的密码:" + password);
}
}
//获取数据库连接
public static Connection getConnectionDB() {
return conn;
}
public static void main(String[] args) {
System.out.println("连接内存地址为:" + ConnectionDB.getConnectionDB());
}
}
private static Connection conn;
//数据库驱动字符串
private String dbdriver = "com.mysql.jdbc.Driver";
//连接数据库URL
private String URL = "jdbc:mysql://localhost:3306/a";
System.out.println("连接数据库成功!");
System.out.println("url:" + URL + ",username:" + username
+ ",password:" + password);
} catch (Exception #34;连接数据库失败!");