JDBC连接问题
我正在使用NetBeans IDE(6.8)。我有一个DB类:JDBC连接问题
package garits;
import java.io.Serializable;
import java.sql.*;
import java.util.Properties;
public class DB implements Serializable{
private static final long serialVersionUID = 1L;
String dbURL = "jdbc:mysql:///team_project";
String user = "root";
String pwd = "arsenal";
String dbDriver = "com.mysql.jdbc.Driver";
private Connection dbCon;
private ResultSet r;
private Statement s;
public DB()
{}
public boolean connect() throws ClassNotFoundException,SQLException{
Class.forName(dbDriver);
Properties props = new Properties();
props.put(user, "root");
props.put(pwd, "arsenal");
props.put("charSet", "UTF-8");
props.put("lc_ctype", "UTF-8");
dbCon = DriverManager.getConnection(dbURL,props);
//dbCon = DriverManager.getConnection(dbURL,user,pwd);
return true;
}
public void close() throws SQLException{
dbCon.close();
if(r!=null)
r.close();
if(s!=null)
s.close();
}
public ResultSet execSQL(String sql) throws SQLException{
s = dbCon.createStatement();
r = s.executeQuery(sql);
return (r == null) ? null : r;
}
public int updateSQL(String sql) throws SQLException{
s = dbCon.createStatement();
int r = s.executeUpdate(sql);
return (r == 0) ? 0 : r;
}
public int updateSQL(String sql, String getID) throws SQLException{
s = dbCon.createStatement();
int autoIncValue = -1;
s.executeUpdate(sql, Statement.RETURN_GENERATED_KEYS);
ResultSet rs = s.getGeneratedKeys();
if (rs.next()) {
autoIncValue = rs.getInt(1);
}
return autoIncValue;
}
}
jar文件即时通讯我的图书馆,但每当我尝试连接:
private void loginButtonActionPerformed(java.awt.event.ActionEvent evt) {
String result ="";
DB db = new DB();
try{
db.connect();
String query = "Select Role From User_Account Where Username=jTextField1.getText()AND Where Password=jTextField2.getText(); ";
ResultSet rs=db.execSQL(query);
while(rs.next())
{
result = rs.getString("Role");
}
if(result.equals(""))
{
JOptionPane.showMessageDialog(loginButton,"Access denied","Error Message",JOptionPane.ERROR_MESSAGE);
}
else if(result.equals("Administrator"))
{
MainPage_Admin admin = new MainPage_Admin();
}
}
catch(Exception e)
{
System.out.println("An error has occurred");
}
}
我得到一个错误(异常被捕获)的-The名数据库是“team_project”,密码是“阿森纳” - 任何想法的赞赏。我是JDBC新手。
第一步:在您的catch-block中使用至少e.printStackTrace()
以从异常中获取一些信息。否则,你只会猜测。
我得到: java.sql.SQLException:访问被拒绝用户''@ localhost' (使用密码:否)为什么我被拒绝访问 - 谢谢。 – 2010-03-26 11:31:15
@eli:因为您没有正确设置用户/密码属性。检查将'user'和'pwd'放入'Properties'的两行:这是错误的。 – 2010-03-26 11:33:32
MySQL数据库的URL连接属性是错误的
jdbc:mysql://localhost:3306/<your database name>
,而不是你给
jdbc:mysql:///team_project
修改并执行该程序,并更好地处理try/catch块中的异常,而不是抛出。
这个JDBC代码还有另一个主要问题:它泄露资源。在尽可能短的范围内以“try-finally”模块获取并关闭它们。示例可以在这里找到:http://balusc.blogspot.com/2008/07/dao-tutorial-data-layer.html – BalusC 2010-03-26 11:38:29