我想在公共类中创建一个函数以获取MySQL连接和显示结果我尝试但是它不起作用这是我的代码当我在主要尝试这个代码时像传统的方式它的工作但是当我尝试放置它在功能上没有任何错误,也没有结果:
import java.sql.*;
/**
*
* @author hammoudi
*/
public class Getconnection {
Connection myConn = null;
Statement myStmt = null;
ResultSet myRs = null;
String user = "root";
String pass = "";
public void serverconnection() throws SQLException {
try {
myConn = DriverManager.getConnection("jdbc:mysql://localhost:3306/soccer", user, pass);
} catch (Exception exc) {
} finally {
if (myConn != null) {
myConn.close();
}
}
}
public void stm() throws SQLException {
try {
myStmt = myConn.createStatement();
} catch (Exception exc) {
} finally {
if (myStmt != null) {
myStmt.close();
}
}
}
public void sqlresult() throws SQLException {
try {
myRs = myStmt.executeQuery("SELECT * FROM `real madrid`");
while (myRs.next()) {
System.out.println(myRs.getString("FirstName") + ", " + myRs.getString("LastName"));
}
} catch (Exception exc) {
} finally {
if (myRs != null) {
myRs.close();
}
}
}
public static void main(String[] args) throws SQLException {
Getconnection connect=new Getconnection();
connect.serverconnection();
connect.stm();
connect.sqlresult();
}
}
答案 0 :(得分:-1)
您遗失Class.forName
,请尝试按以下方式添加:
Class.forName("com.mysql.jdbc.Driver");
myConn = DriverManager.getConnection("jdbc:mysql://localhost:3306/soccer", user, pass);
答案 1 :(得分:-1)
//你应该试试这个
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost:3306/soccer";
static final String USER = "root";
static final String PASS = "";
static Connection conn = null;
public static void connect() {
try {
Class.forName(JDBC_DRIVER);
conn = DriverManager.getConnection(DB_URL, USER, PASS);
} catch (Exception e) {
e.printStackTrace();
}
}
public static Connection getConnection() throws Exception {
connect();
if (conn != null)
return conn;
else {
throw new Exception("Can not connect");
}
}}
答案 2 :(得分:-1)
首先应该建立连接,试试这个:
放置此行
Class.forName("com.mysql.jdbc.Driver");
在此之前
myConn = DriverManager.getConnection("jdbc:mysql://localhost:3306/soccer", user, pass);
快乐的编码!!