【发布时间】:2013-07-03 07:31:44
【问题描述】:
代码有什么问题,调试时有很多错误。我正在为单例类编写代码以连接数据库 mysql。
这是我的代码
package com.glomindz.mercuri.util;
import java.sql.Connection;
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.SQLException;
public class MySingleTon {
String url = "jdbc:mysql://localhost:3306/";
String dbName = "test";
String driver = "com.mysql.jdbc.Driver";
String userName = "root";
String password = "";
private static MySingleTon myObj;
private Connection Con ;
private MySingleTon() {
System.out.println("Hello");
Con= createConnection();
}
@SuppressWarnings("rawtypes")
public Connection createConnection() {
Connection connection = null;
try {
// Load the JDBC driver
Class driver_class = Class.forName(driver);
Driver driver = (Driver) driver_class.newInstance();
DriverManager.registerDriver(driver);
connection = DriverManager.getConnection(url + dbName);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
}
return connection;
}
/**
* Create a static method to get instance.
*/
public static MySingleTon getInstance() {
if (myObj == null) {
myObj = new MySingleTon();
}
return myObj;
}
public static void main(String a[]) {
MySingleTon st = MySingleTon.getInstance();
}
}
我是 Java 新手。请帮忙。
【问题讨论】:
-
驱动 jar 在你的类路径中吗?
-
确保您已在 getInstance() 上同步
-
如果您在运行时遇到错误,您需要将 jar 文件粘贴到您的网络服务器的 lib 目录中。但是,如果您在编译时遇到错误,请在构建路径中添加 jar。
标签: java jdbc mysql-connector