测试所有建议的解决方案时无法连接到jdbc

时间:2015-12-01 09:08:04

标签: java mysql jdbc

我正在尝试连接到笔记本电脑上的mysql。使用我粘贴在下面的代码。我添加了 CLASSPATH ,其中包含文件的完整路径:

mysql-connector-java-5.1.37-bin.jar

然后导出它。但是我坚持不断提到错误。有人可以告诉我,我错过了什么让我从我的机器上得到这个错误信息。

我的机器是Fedora核心21,我试图在用户下执行代码,而不是root,这是我正在使用的代码,当然静态最终变量“user”和“password”不是空的他们在这里的字符串:

//STEP 1. Import required packages

import java.sql.*;

public class JDBCExample {
  // JDBC driver name and database URL    
   static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";  
   static final String DB_URL = "jdbc:mysql://localhost/";

   //  Database credentials   
   static final String USER = "";    
   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 connect ion    
      System.out.println("Connecting to database...");    
      conn = DriverManager.getConnection(DB_URL, USER, PASS);    
      //STEP 4: Execute a query   
      System.out.println("Creating database...");    
      stmt = conn.createStatement();          
      String sql = "CREATE DATABASE STUDENTS";    
      stmt.executeUpdate(sql);    
      System.out.println("Database created successfully...");    
   }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   
   System.out.println("Goodbye!");    
}//end main    
}//end JDBCExample

我确实试图包含任何可以猜测它相关的相关信息。如果需要更多信息来回答我愿意提供的问题。

1 个答案:

答案 0 :(得分:-2)

DB_URL应该设置MySQL的端口和数据库名称。

就像(windows):

jdbc\:mysql\://111.202.27.131\:3306/bridgeResultDatabase?characterEncoding\=utf8

这里bridgeResultDatabase是mysql数据库名称,它适用于我。

希望它有所帮助。

上面有一些错误。 更新(我在我的Windows中尝试并在Linux中使用mysql的根目录):

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;

public static void main(String[] args) throws ClassNotFoundException, SQLException{
    String JDBC_DRIVER="com.mysql.jdbc.Driver";
    String DB_URL="jdbc:mysql://192.168.11.52/mysql";
    Class.forName(JDBC_DRIVER);
    Connection conn = DriverManager.getConnection(DB_URL,"root","111111");
    Statement statement = conn.createStatement();
    String hrappSQL = "CREATE DATABASE testDatabase";
    statement.executeUpdate(hrappSQL);
}

我在linux mysql中成功创建了数据库“testDatabase”。