如何通过java程序访问另一个系统的mysql数据库? [英] How to access the another system mysql database through java program?
问题描述
如何通过java程序访问另一个系统的mysql数据库?我正在使用下面的程序,但出现通信错误?连接另一个系统的mysql数据库需要做哪些更改?
How to access the another system mysql database through java program?Am using the following program but i have get the communication error?what are the changes are need to connect the another system mysql database?
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);
}
}
推荐答案
您不是在创建驱动程序类的实例:
You're not creating an instance of the driver class:
Class.forName("com.mysql.jdbc.Driver").newInstance();
[更新:毕竟没有必要,忽略这一点]
[update: not necessary after all, ignore that]
而且您还引用了sun.jdbc.odbc.JdbcOdbcDriver",这有必要吗?如果是这样,你不应该也实例化它吗?[更新:可能不是]
And you're also referencing "sun.jdbc.odbc.JdbcOdbcDriver", is that necessary? If so, shouldn't you instantiate it also? [update: probably not]
如果它适用于 localhost,而不是指定的 IP,则需要配置 mysql 以侦听所有端口.
If it works with localhost, and not with the IP specified, you need to configure mysql to listen on all ports.
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
这篇关于如何通过java程序访问另一个系统的mysql数据库?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!