Can';t使用java成功连接到mysql数据库
因此,该数据库的目的是执行访问该数据库的网站所需的查询,以下是代码:Can';t使用java成功连接到mysql数据库,java,mysql,Java,Mysql,因此,该数据库的目的是执行访问该数据库的网站所需的查询,以下是代码: package dodRus; //STEP 1. Import required packages import java.sql.*; public class Connect_Database { // JDBC driver name and database URL static final String JDBC_DRIVER = "com.mysql.jdbc.Driver"; static fina
package dodRus;
//STEP 1. Import required packages
import java.sql.*;
public class Connect_Database {
// JDBC driver name and database URL
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://127.0.0.1:3306/?user=root";
// Database credentials
static final String USER = "root";
static final String PASS = ;
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
try{
//STEP 2: Register JDBC driver
Class.forName("com.mysql.jdbc.Driver");
//STEP 3: Open a connection
System.out.println("Connecting to database...");
conn = DriverManager.getConnection(DB_URL,USER,PASS);
//STEP 4: Execute a query
System.out.println("Creating statement...");
stmt = conn.createStatement();
String sql;
sql = "INSERT INTO Inventory " + "VALUES (shirt,1234,5)";
stmt.executeUpdate(sql);
}catch(SQLException se){
//Handle errors for JDBC
se.printStackTrace();
}catch(Exception e){
//Handle errors for Class.forName
e.printStackTrace();
}finally{
//finally block used to close resources
try{
if(stmt!=null)
stmt.close();
}catch(SQLException se2){
}// nothing we can do
try{
if(conn!=null)
conn.close();
}catch(SQLException se){
se.printStackTrace();
}//end finally try
}//end try
}
}
下面是错误:
显然,它没有成功连接到数据库,但我不明白为什么需要在DSN字符串中包含数据库名称
static final String DB_URL = "jdbc:mysql://127.0.0.1:3306/<name_of_database>?user=" + USER + "&password=" + PASS;
静态最终字符串DB_URL=“jdbc:mysql://127.0.0.1:3306/?user=“+USER+”&password=“+PASS;
请参阅。我真的希望您没有在示例代码中发布真实的root密码…即使是localhost,也不希望以您从未在url中指定要使用的数据库名称的方式发布它。错误就在那里。url应该是
jdbc:mysql://127.0.0.1:3306/(此处为数据库名称)?user=root
static final String DB_URL = "jdbc:mysql://127.0.0.1:3306/<name_of_database>?user=" + USER + "&password=" + PASS;