Linux系统下Java连接Mysql数据库方法与Windows下类似,具体步骤如下:
下载JDBC(驱动):mysql-connector-java-5.1.29.tar.gz
解压下载的数据包:tar -zxvf mysql-connector-java-5.1.29.tar.gz
配置JDBC:cp mysql-connector-java-5.1.29-bin.jar /usr/lib/jvm/java-1.7.0-openjdk-i386/jre/lib/ext/
解压后,mysql-connector-java-5.1.29-bin.jar位于mysql-connector-java-5.1.29目录下。另外,在
Ubuntu系统中,如果你使用是apt-get install命令安装的jdk,那么一般的安装目录是:/usr/lib/jvm。你还必须明白的是:此步的目的是将连接驱动拷贝到Java的安装目录下,你必须保证Java环境变量设置正确(apt-get命令安装jdk环境变量不需自己修改),否则后面的Java程序无法找到JDBC。
示例代码:
//package org.gsfan.clustermonitor.dbconnector;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class MysqlConnector {
private String userName = null;
private String passwd = null;
private String sql = null;
private Connection connection = null;
private PreparedStatement preStatement = null;
private ResultSet resultSet = null;
private static final String dbDriver = "com.mysql.jdbc.Driver";
// private static final String dbDriver = "org.gjt.mm.mysql.Driver";
// private static final String dbURL = "jdbc:mysql://192.168.233.130:3306/clusteruser";
private static final String dbURL = "jdbc:mysql://localhost:3306/clusteruser";//使用主机IP会出错,这是为什么?
public MysqlConnector(String userName, String passwd){
this.userName = userName;
this.passwd = passwd;
try {
Class.forName(dbDriver) ;
} catch (ClassNotFoundException e1) {
e1.printStackTrace();
// String sql = "insert into clusteruser values(2,'gsfan','0620631FGS')";
try {
connection = DriverManager.getConnection(dbURL, this.userName, this.passwd);
// preStatement = connection.prepareStatement(sql);
// preStatement.executeUpdate();
sql = "select * from clusteruser";
preStatement = connection.prepareStatement(sql);
resultSet = preStatement.executeQuery();
while(resultSet.next()){//没有resultSet.next()会出现异常
System.out.println("userName = "+resultSet.getString(2)+"\t password = "+resultSet.getString(3));
}
} catch (SQLException e) {
e.printStackTrace();
}
}
public static void main(String[] args){
MysqlConnector connector = new MysqlConnector("root", "0620631FGS");
}
}<span style="color:#ff0000;">
</span>
编译运行:
--转自