【eclipse】连接mysql

来源:互联网 发布:中俄原油管道 知乎 编辑:程序博客网 时间:2024/06/03 13:17

java连接mysql时,需要安装驱动。如果未安装,会出现找不到“com.mysql.jdbc.Driver”的错误。

最新版驱动是:mysql-connector-java-5.1.22

下载地址:http://pan.baidu.com/share/link?shareid=64178&uk=2585386604

安装驱动程序:

1、下载jdbc的驱动,解压到任一位置中

2、打开eclipse,找到再在windows->preferences->java->installed jres

3、单击Sun JDk….,然后单击edit

4、点击add external jars,选择压缩包中的mysql-connector-java-5.1.22-bin.jar

5、点击finish

使用下面的程序测试数据库连接:

import java.sql.*;
public class JDBCTest {
public static void main(String[] args){
// 驱动程序名
String driver = "com.mysql.jdbc.Driver";
// URL指向要访问的数据库名game
String url = "jdbc:mysql://127.0.0.1:3306/game";
// MySQL配置时的用户名
String user = "root";
// MySQL配置时的密码
String password = "root";
try {
// 加载驱动程序
Class.forName(driver);
// 连续数据库
Connection conn = DriverManager.getConnection(url, user, password);
if(!conn.isClosed())
System.out.println("Succeeded connecting to the Database!");
// statement用来执行SQL语句
Statement statement = conn.createStatement();
// 要执行的SQL语句
String sql = "select id,username from user_index order by id desc limit 0,5";
// 结果集
ResultSet rs = statement.executeQuery(sql);
System.out.println("-----------------");
System.out.println("执行结果如下所示:");
System.out.println("-----------------");
System.out.println(" id" + "\t" + " 用户名");
System.out.println("-----------------");
String name = null;
while(rs.next()) {
// 选择username这列数据
name = rs.getString("username");
// 首先使用ISO-8859-1字符集将name解码为字节序列并将结果存储新的字节数组中。
// 然后使用GB2312字符集解码指定的字节数组
name = new String(name.getBytes("ISO-8859-1"),"GB2312");
// 输出结果
System.out.println(rs.getString("id") + "\t" + name);
}
rs.close();
conn.close();
} catch(ClassNotFoundException e) {
System.out.println("Sorry,can`t find the Driver!");
e.printStackTrace();
} catch(SQLException e) {
e.printStackTrace();
} catch(Exception e) {
e.printStackTrace();
}
}
}

0 0
原创粉丝点击