首先,我正在考虑我的答案,以向您展示与MySQL数据库进行连接的另一种更好的方法,它更容易使用,并且nu-expected Exception 更少。
您需要执行一些步骤:
- 下载Connector / J并将其添加到您的类路径中(如果您使用的是IDE,则将其添加
.jar
到库中,或者YouTube上有很多tut )。 - 在MySQL程序中创建数据库。
请参见下面为我提供的示例,下面的示例演示了如何在MySQL上连接和执行查询:
import java.sql.*;
public class MySqlConnection {
private String MYSQL_DRIVER = “com.mysql.jdbc.Driver”;
private String MYSQL_URL = “jdbc:mysql://localhost:3306/test”;private Connection con;
private Statement st;
private ResultSet rs;public MySqlConnection() {
try { Class.forName(MYSQL_DRIVER); System.out.println("Class Loaded...."); con = DriverManager.getConnection(MYSQL_URL,"",""); System.out.println("Connected to the database...."); st = con.createStatement(); int c =st.executeUpdate("CREATE TABLE Accounts (Name VARCHAr(30))"); System.out.println("Table have been created."); System.out.println(c+" Row(s) have been affected"); con.close();} catch(ClassNotFoundException ex) { System.out.println("ClassNotFoundException:n"+ex.toString()); ex.printStackTrace();} catch(SQLException ex) { System.out.println("SQLException:n"+ex.toString()); ex.printStackTrace();}}
public static void main(String…args) {
new MySqlConnection();
}
}



