您的位置:首页 > 编程语言 > Java开发

在Eclipse中用JDBC连接Mysql数据库

2013-08-26 17:41 316 查看
一、配置要求

JDK(下载http://www.oracle.com/technetwork/java/javase/downloads/index.html)
Mysql(下载http://www.mysql.com/downloads/)
JDBC驱动(下载http://www.oracle.com/technetwork/java/javase/jdbc/index.html
Eclipse(下载http://www.eclipse.org/downloads/)
二、安装

         JDK、Mysql、Eclipse的安装就不赘述了,解压缩到你放JDBC驱动程序的位置就可以了,不需要安装。然后设置Classpath环境变量,在Classpath环境变量里添加JDBC驱动程序,如我的是添加D:\Work Software\mysql-connector-java-5.0.8\mysql-connector-java-5.0.8-bin.jar 。注意,要是用Eclipse运行java文件时要在配置路径下添加mysql-connector-java-5.0.8-bin.jar文件。步骤为:右键你要添加的项目-->Build
path-->Configure Build path..-->Libraries-->Add External Jars然后选择文件所在路径。

三、建立数据库

       用数据库管理软件(我是用Navacat)建立数据库,演示中数据库名称为school,students表,表中包括ID,Name,Age字段。

四、编写代码

import java.sql.*;

public class JDBCTest {

public static void main(String[] args){
// 驱动程序名
String driver = "com.mysql.jdbc.Driver";
// URL指向要访问的数据库名school
String url = "jdbc:mysql://127.0.0.1:3306/school";
// MySQL配置时的用户名
String user = "root";
// MySQL配置时的密码
String password = "123456";
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 * from students";
// 结果集
ResultSet rs = statement.executeQuery(sql);
System.out.println("-----------------");
System.out.println("执行结果如下所示:");
System.out.println("-----------------");
System.out.println(" 学号" + "\t" + " 姓名");
System.out.println("-----------------");
String name = null;
while(rs.next()) {
// 选择Name这列数据
name = rs.getString("Name");
// 首先使用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();
}
}
}


参考:http://www.cnblogs.com/soplayer/archive/2007/06/26/796565.html

  
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  mysql jdbc eclipse java