Java数据库连接(Java DataBase connectivity简称JDBC)
Windows系统下载.zip文件包,Linux平台下载tar.gz文件包
解压后找gcfjmysql-connector-java-[version]-bin.jar包,JDBC通过这个文件才可以正确的连接数据库。
打开Eclipse—— 右击项目——Build Path——Add External JARs 浏览刚才下载的jar包。
Apply and Close 后,在项目目录中可以找刚才添加的jar包
接下来我们新建DBHelper简单的数据访问类,代码如下:
package com.llt.demo; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; public class DBHelper { public static final String url = "jdbc:mysql://127.0.0.1/test"; // jdbc:mysql://host:port/database name public static final String name = "com.mysql.jdbc.Driver"; public static final String user = "root"; // 数据库登录用户 public static final String password = "123456"; public Connection connection = null; public PreparedStatement pst = null; // 数据库登录密码 public DBHelper(String sql) { try { Class.forName(name);// 指定连接类型 connection = DriverManager.getConnection(url, user, password);// 创建连接 pst = connection.prepareStatement(sql);// 执行Sql语句 } catch (Exception e) { e.printStackTrace(); } } public void close() { try { this.connection.close(); this.pst.close(); } catch (Exception e) { } } }
然后创建一个简单的类,测试连接一下MySQL数据库
package com.llt.demo; import java.sql.ResultSet; public class test { public static String sql = ""; public static DBHelper db = null; public static ResultSet ret = null; public static void main(String[] args) { // TODO Auto-generated method stub String sql = "select * from book"; db = new DBHelper(sql); try { ret = db.pst.executeQuery(); while (ret.next()) { int id = ret.getInt(1); String name = ret.getString(2); System.out.println("id:" + id + ",name:" + name); } // 使用完后将数据库连接关闭 ret.close(); db.close(); } catch (Exception e) { e.printStackTrace(); } } }
输出MySQL数据库book表中的内容: