我添加了JAR文件“mysql-connector-java-5.1.36-bin”,并创建了数据库“UserScore”,并在该表“ScoreSheet”下。我在ScoreSheet(Name,Score)值中添加了一行( 'Kamal',40)验证但是代码在连接上引发了很多异常。我正在使用Eclipse + Xampp。
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
public class SQLDriver{
public static void main(String[] args){
try{
//Accessing driver from jar file
Class.forName("com.mysql.jdbc.Driver");
//Get connection through creating a variable 'myConn'
Connection myConn = DriverManager.getConnection("jdbc:mysql://localhost:3306/UserScores");
//Create statement
PreparedStatement statement = myConn.prepareStatement("select * from 'scoresheet'");
//Execute SQL Query
ResultSet result = statement.executeQuery();
//Process the result set
while(result.next()){
System.out.println(result.getString(1)+" "+result.getString(2));
}
}
catch(Exception e){
e.printStackTrace();
}
}
}
答案 0 :(得分:0)
Scoresheet
而不'
DriverManager.getConnection
result.getInt(2)
而不是result.getString(2)
答案 1 :(得分:0)
我总是这样做:
// Hostname
private static final String dbHost = "127.0.0.1";
// Port -- Standard: 3306
private static final String dbPort = "3306";
// Database name
private static String database = "database"; //
// Database user
private static final String dbUser = "root";
// Datenbankpasswort
private static final String dbPassword = "";
private Statement s;
public void Connect() {
try {
Class.forName("java.sql.Driver"); // load driver
Connection conn = DriverManager.getConnection("jdbc:mysql://" + dbHost + ":"
+ dbPort + "/" + database + "?" + "user=" + dbUser + "&"
+ "password=" + dbPassword); // try to connect with your attributes
s = conn.createStatement();
} catch (ClassNotFoundException e) { //
l.error("Driver not found " + e);
} catch (SQLException e) {
l.error("Connect not possible" + e);
}
}