我似乎无法做到这一点:
import com.mysql.jdbc.Connection;
import java.sql.DriverManager;
public class connect {
public static Connection sqlconnect;
public static Connection OpenDB()
{
String database = "jdbc:mysql://localhost:3306/library";
String user = "root";
String password = "";
if (sqlconnect == null){
try{
DriverManager.registerDriver(new com.mysql.jdbc.Driver());
sqlconnect = (Connection) DriverManager.getConnection(database, user, password);
System.out.print("Connection Passed");
}
catch (Exception e){
System.out.print("Connection Failed!");
}
}
return sqlconnect;
}
}
我尝试了很多我在网上看到的代码而且没有一个代码可以正常工作,每次使用此代码时都没有出现任何错误,但是如果我发现错误,它就不会打印或显示给我我在数据库中连接。我将它用作按钮中的对象。
我用这个来调用对象:
private void btnSubmitActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
connect c = new connect();
}
答案 0 :(得分:0)
import java.sql.*;
public class FirstExample {
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost/databasename";
static final String USER = "root";
static final String PASS = "password";
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
try{
Class.forName("com.mysql.jdbc.Driver");
System.out.println("Connecting to database...");
conn = DriverManager.getConnection(DB_URL,USER,PASS);
System.out.println("Creating statement...");
stmt = conn.createStatement();
String sql;
sql = "select * from tablename";
ResultSet rs = stmt.executeQuery(sql);
while(rs.next()){
String first = rs.getString(1);
String last = rs.getString(2);
System.out.print(", First: " + first);
System.out.println(", Last: " + last);
}
rs.close();
stmt.close();
conn.close();
}catch(SQLException se){
se.printStackTrace();
}catch(Exception e){
e.printStackTrace();
}finally{
try{
if(stmt!=null)
stmt.close();
}catch(SQLException se2){
}
try{
if(conn!=null)
conn.close();
}catch(SQLException se){
se.printStackTrace();
}
}
}
}
复制上面的代码并添加mysql-connector-java-5.0.8-bin
jar文件。并运行它eclipse。但请确保数据库名称和用户名,密码详细信息有效。