我想从mysql在另一个系统中的java代码连接到mysql。 我在另一台机器“nilotpal”中创建了一个用户。 其他机器地址是192.168.92.93。 我能ping到这台机器。我错过了哪里?有人可以帮忙吗?!!
我正在使用的程序是:
import java.sql.*;
public class FirstExample {
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://192.168.92.93:3306/tution";
// Database credentials
static final String USER = "nilotpal";
static final String PASS = "nilotpal";
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 = "SELECT id, first, last, age FROM Employees";
ResultSet rs = stmt.executeQuery(sql);
//STEP 5: Extract data from result set
while(rs.next()){
//Retrieve by column name
int id = rs.getInt("id");
int age = rs.getInt("age");
String first = rs.getString("first");
String last = rs.getString("last");
//Display values
System.out.print("ID: " + id);
System.out.print(", Age: " + age);
System.out.print(", First: " + first);
System.out.println(", Last: " + last);
}
//STEP 6: Clean-up environment
rs.close();
stmt.close();
conn.close();
}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 FirstExample
答案 0 :(得分:1)
首先使用ping命令ping机器,如果是ping,则检查mysql用户权限。
向用户授予权限:
创建用户'newuser'@'localhost'通过'密码'识别;
授予所有特权*。 *到'newuser'@'localhost';
FLUSH PRIVILEGES;
答案 1 :(得分:1)
来自Connect to mysql on a different server
的参考资料还要确保mysql用户nilotpal具有远程连接权限。其他明智的mysql-server将不允许您的nilotpal用户远程登录。即来自您的服务器(来自程序)。
您可以确保从mysql.user表。
mysql> select Host,User from user where User = "root";
+------------+------+
| Host | User |
+------------+------+
| 127.0.0.1 | root |
| ::1 | root |
| localhost | root |
| sgeorge-mn | root |
| % | root |
+------------+------+
4 rows in set (0.01 sec)
%表示任何主机。
要创建具有远程连接权限的用户,请使用以下mysql查询:
mysql> CREATE USER 'nilotpal'@'%' IDENTIFIED BY 'nilotpal';