标签:
1、JDBC是SUN公司为了简化操作数据推出一套规范。数据库厂商的驱动就是对JDBC的实现。
2、Java Data Base Connectivity(java数据库连接),它主要由接口组成。
java.sql.* javax.sql.* JDK中
数据库的驱动jar包 (mysql-connector-java-5.0.8-bin.jar )
0、前提:拷贝数据库的驱动到构建路径中(classpath)
1、注册驱动
2、获取与数据库的链接
3、创建代表SQL语句的对象
4、执行SQL语句
5、如果是查询语句,需要遍历结果集
6、释放占用的资源
public class JdbcDemo1 { public static void main(String[] args) throws SQLException { // 1、注册驱动 DriverManager.registerDriver(new com.mysql.jdbc.Driver()); // 2、获取与数据库的链接 Connection conn = DriverManager.getConnection( "jdbc:mysql://localhost:3306/day15", "root", ""); //没有密码则“” 空 // System.out.println(conn.getClass().getName()); 要想知道具体类型,就这么办 // 3、创建代表SQL语句的对象 Statement stmt = conn.createStatement(); // 4、执行SQL语句 ResultSet rs = stmt.executeQuery("select id,name,password,email,birthday from users"); // 5、如果是查询语句,需要遍历结果集 while (rs.next()) { System.out.println("---------------------"); System.out.println(rs.getObject("id")); System.out.println(rs.getObject("name")); System.out.println(rs.getObject("password")); System.out.println(rs.getObject("email")); System.out.println(rs.getObject("birthday")); } // 6、释放占用的资源 rs.close(); stmt.close(); conn.close(); } }
1、DriverManager:
作用:
a、注册驱动:
方式一:(不建议使用)
DriverManager.registerDriver(new com.mysql.jdbc.Driver());
原因:1、依赖具体驱动。2、导致驱动注册2遍
方式二:(建议)
Class.forName("com.mysql.jdbc.Driver");
b、获取与数据库的链接
url:SUN和数据库厂商间的协议。具体查阅数据库的文档。
public static Connection getConnection(String url,String user,String password)
throws SQLException
public static Connection getConnection(String url,Properties info)
throws SQLException
public static Connection getConnection(String url)
throws SQLException
2、Connection
所有的数据库操作都是基于链接之上的。
Statement createStatement():创建向数据库发送sql的statement对象。
//2、获取与数据库的链接 //方式一: //Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/day15", "root", "sorry"); //方式二: //Properties props = new Properties(); //props.setProperty("user", "root");// 参数名:参考数据库的文档 //props.setProperty("password", "sorry"); //props.setProperty("useUnicode", "true");//编码有关的参数 //props.setProperty("characterEncoding", "utf8"); //Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/day15",props); //方式三 Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/day15?user=root&password=sorry");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/day15?user=root&password=");
3、Statement
Statement stmt = conn.createStatement();
作用:代表SQL语句对象。可以向数据库发送任何的SQL语句
ResultSet executeQuery(String sql):sql一般都是查询语句
int executeUpdate(String sql):sql一般是DML语句。insert update delete。返回值,操作几条记录。
boolean execute(String sql):sql可以是任意的语句。返回值不是代表成功与否。如果是查询语句,就有结果集,返回true。没有返回结果集的,返回false。
4、ResultSet
作用:封装了查询的结果集
ResultSet rs = stmt.executeQuery("select id,name,password,email,birthday from users"); List<User> users = new ArrayList<User>(); while(rs.next()){ User user = new User(); user.setId(rs.getInt("id")); user.setName(rs.getString("name")); user.setPassword(rs.getString("password")); user.setEmail(rs.getString("email")); user.setBirthday(rs.getDate("birthday")); users.add(user); }
boolean next():游标下移。返回值是有无记录
boolean previous():游标上移。
boolean absolute(int count):定位到指定的行。第一行是1。
void beforeFirst():移动游标到第一行的前面。
void afterLast():移动游标到最后一行的后面。
//释放资源 //JDBC编码的代码模板 public class JdbcDemo5 { public static void main(String[] args) { Connection conn = null; Statement stmt = null; ResultSet rs = null; try { Class.forName("com.mysql.jdbc.Driver"); conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/day15", "root", "sorry"); stmt = conn.createStatement(); rs = stmt.executeQuery("select id,name,password,email,birthday from users"); List<User> users = new ArrayList<User>(); while (rs.next()) { User user = new User(); user.setId(rs.getInt("id")); user.setName(rs.getString("name")); user.setPassword(rs.getString("password")); user.setEmail(rs.getString("email")); user.setBirthday(rs.getDate("birthday")); users.add(user); } } catch (Exception e) { e.printStackTrace(); }
finally { if (rs != null) { try { rs.close(); } catch (SQLException e) { e.printStackTrace(); } rs = null; } if (stmt != null) { try { stmt.close(); } catch (SQLException e) { e.printStackTrace(); } stmt = null; } if (conn != null) { try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } conn = null; } } } }
工具類:
getConnection() return conn; 獲取連接
配置文件放在 dbcgf.properties 中
release () 施放資源
//工具类 public class JdbcUtil { private static String driverClass; private static String url; private static String user; private static String password; static{ try { ClassLoader cl = JdbcUtil.class.getClassLoader(); InputStream in = cl.getResourceAsStream("dbcfg.properties"); Properties props = new Properties(); props.load(in); driverClass = props.getProperty("driverClass"); url = props.getProperty("url"); user = props.getProperty("user"); password = props.getProperty("password"); Class.forName(driverClass); } catch (Exception e) { throw new ExceptionInInitializerError(e); } } public static Connection getConnection() throws Exception{ Connection conn = DriverManager.getConnection(url,user, password); return conn; } public static void release(ResultSet rs,Statement stmt,Connection conn){ if(rs!=null){ try { rs.close(); } catch (SQLException e) { e.printStackTrace(); } rs = null; } if(stmt!=null){ try { stmt.close(); } catch (SQLException e) { e.printStackTrace(); } stmt = null; } if(conn!=null){ try { conn.close(); ] catch (SQLException e) { e.printStackTrace(); } conn = null; } } }
測試:
package com.yif.jdbc; import java.sql.Connection; import java.sql.ResultSet; import java.sql.Statement; import org.junit.Test; import com.yif.util.JdbcUtil; public class JdbcDemo6 { @Test public void testAdd(){ Connection conn = null; Statement stmt = null; ResultSet rs = null; try{ conn = JdbcUtil.getConnection(); stmt = conn.createStatement(); stmt.executeUpdate("insert into users (name,password,email,birthday) values (‘范青霞‘,‘123‘,‘fqx@itcast.cn‘,‘2000-10-01‘)"); }catch(Exception e){ throw new RuntimeException(e); }finally{ JdbcUtil.release(rs, stmt, conn); } } @Test public void testUpdate(){ Connection conn = null; Statement stmt = null; ResultSet rs = null; try{ conn = JdbcUtil.getConnection(); stmt = conn.createStatement(); stmt.executeUpdate("update users set password=111 where id=4"); }catch(Exception e){ throw new RuntimeException(e); }finally{ JdbcUtil.release(rs, stmt, conn); } } @Test public void testDelete(){ Connection conn = null; Statement stmt = null; ResultSet rs = null; try{ conn = JdbcUtil.getConnection(); stmt = conn.createStatement(); stmt.executeUpdate("delete from users where id=1"); }catch(Exception e){ throw new RuntimeException(e); }finally{ JdbcUtil.release(rs, stmt, conn); } } }
标签:
原文地址:http://www.cnblogs.com/FLFL/p/5251835.html