如何通过java程序访问另一个系统mysql数据库?我使用以下程序但是我得到了通信错误?有什么变化需要连接另一个系统的mysql数据库?
Public void dbconnection() {
String name = "";
String port = "3306";
String user = "system";
String pass = "system";
String dbname = "cascade_demo";
String host="192.168.1.61";
try {
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://"+host+":"+ port + "/" + dbname;
System.out.println("URL:" + url);
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con = DriverManager.getConnection(url, user, pass);
String qry2 = "select * from item_master";
Statement st = con.createStatement();
ResultSet rs = st.executeQuery(qry2);
while (rs.next()) {
name = rs.getString(1);
System.out.println("Name:" + name);
}
rs.close();
st.close();
con.close();
} catch (Exception e) {
System.out.println("Exception:" + e);
}
}
答案 0 :(得分:0)
您没有创建驱动程序类的实例:
Class.forName("com.mysql.jdbc.Driver").newInstance();
[更新:毕竟没有必要,忽略它]
你还引用了“sun.jdbc.odbc.JdbcOdbcDriver”,这是必要的吗?如果是这样,你不应该实例化吗? [更新:可能不会]
如果它适用于localhost,而不是指定的IP,则需要配置mysql以侦听所有端口。
jcomeau@intrepid:/tmp$ cat dbconnection.java; javac dbconnection.java; sudo java -cp .:/usr/share/maven-repo/mysql/mysql-connector-java/5.1.16/mysql-connector-java-5.1.16.jar dbconnection
import java.sql.*;
public class dbconnection {
public static void main(String args[]) {
String name = "";
String port = "3306";
String user = "root";
String pass = "";
String dbname = "imagetagging";
String host="127.0.0.1";
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
String url = "jdbc:mysql://"+host+":"+ port + "/" + dbname;
System.out.println("URL:" + url);
//Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con = DriverManager.getConnection(url, user, pass);
String qry2 = "select * from taggers";
Statement st = con.createStatement();
ResultSet rs = st.executeQuery(qry2);
while (rs.next()) {
name = rs.getString(1);
System.out.println("Name:" + name);
}
rs.close();
st.close();
con.close();
} catch (Exception e) {
System.out.println("Exception:" + e);
}
}
}
URL:jdbc:mysql://127.0.0.1:3306/imagetagging
Name:1
Name:2
Name:3
Name:4
Name:5
Name:6
Name:7
Name:8
Name:9
Name:10
Name:11
Name:12
Name:13
Name:14
Name:15
Name:16
Name:17
Name:18
Name:19
Name:20
Name:21
答案 1 :(得分:0)
据我所知,您只需要指定另一个连接字符串,另一个主机和其他凭据,例如:
...
String port = "3306";
String user = "user_name";
String pass = "password";
String dbname = "db_name";
String host="host_name";
...
答案 2 :(得分:0)
你必须做3个(带第4步可选)简单的事情来连接你的远程mysql数据库服务器。
在how to enable remote access to your db上查看此帖子,然后重试(转到第1页)
你需要清理一下你的代码,看看如何用Vogella tutorial上的java连接和执行简单的sql语句的简单教程