package com.sample;
import java.sql.DriverManager;
import com.mysql.jdbc.Connection;
public class connectionclass {
public static void main(String args) {
System.out.println("MySql Connect Example");
Connection conn = null;
String url = "jdbc:mysql://localhost:3306/";
String dbName = "testdatabase";
String driver = "com.mysql.jdbc.Driver";
String userName = "root";
String password = "root";
try {
Class.forName(driver).newInstance();
conn = (Connection) DriverManager.getConnection(url + dbName,
userName, password);
System.out.println("Connected to the database");
conn.close();
System.out.println("Disconnected from database");
} catch (Exception e) {
e.printStackTrace();
}
}
}
此代码连接到数据库并且没有给出语法错误。我在 Eclipse 中执行此操作,当我运行项目时,它会询问我们需要运行哪个类,但我的类不存在。