zoukankan      html  css  js  c++  java
  • JDBC基本应用

    首先我们来看一下JDBC操作数据的核心:

    Connection

    应用程序与数据库之间的桥梁

    数据库驱动程序是构建桥梁的基石和材料

    DriverManager类是基石和材料的管理员

    Statement

    桥梁上的汽车。在应用程序和数据库之间运送SQL语句和运行结果

    ResultSet

    运行查询得到的数据集。由若干行和列组成的数据表,是数据库中数据表的子集,有游标

    JDBC基本步骤:

    1 注冊驱动

    Class.forName(“com.mysql.jdbc.Driver”);

    2 建立到数据库的连接

    Connection con = DriverManager.getConnection(

    "jdbc:mysql://localhost:3306/test?user=root&password=root");

    3 创建statement

    Statement  stmt = con.createStatement();

    4 运行SQL语句

    int  count= stmt.executeUpdate(“update  student  set  age=25  where  id=1”);

    ResultSet  rs= stmt.executeQuery(“select  *  from  student”);

    5 处理results

    while(rs.next()){  

        rs.getString(2); 

    }

    对数据进行加入、删除、改动等操作,SQL运行结束就已经完毕

    对数据进行查询,查询结果存放在ResultSet对象中

    ResultSet对象是满足查询条件的数据行。是数据库表数据的子集

    ResultSet

    使用游标指向数据行

    游标最初定位在第一行之前

    boolean  rs.next();

    当游标指向某行数据,我们就能够从当前行取出须要的数据


    在ResultSet对象中使用getXXX(索引或列名)方法获得数据

    使用列名称或索引检索数据

    rs.getString(2);
    rs.getInt(“age”);


    6 关闭JDBC对象

        try {
            if(rs!=null){  rs.close();  }
            if(stmt!=null){  stmt.close();  }
            if(conn!=null){  conn.close();  }
        } catch (SQLException e) {  
    e.printStackTrace();  
        } 


    某些步骤的实现方式有多种。比方:注冊驱动……

    注冊驱动的方式有多种

    1)使用类装载器(Class.forName(“类名”))

    Class.forName(“com.mysql.jdbc.Driver”);

    2)使用newkeyword实例化驱动类

    3)在属性文件里配置jdbc.drivers属性

    4)省略驱动程序注冊步骤

    使用JDBC4.0以上版本号

    ----------------------------------------------------------------------------------------------------------------------------------------------------------------------

    能够使用newkeyword对驱动进行显式的实例化

    语法:

    Driver drv = new DriverConstructor();
    DriverManager.registerDriver(drv);


    在配置文件里指定驱动类名

    语法:
    jdbc.drivers = driverName

    演示样例:

    //创建一个test.properties配置文件,在属性文件里写入属性并赋值

    //然后在程序中读取配置文件

    jdbc.drivers= com.mysql.jdbc.Driver

    下面是具体代码:

    package util;
    
    import java.io.BufferedInputStream;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.PreparedStatement;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    import java.sql.Statement;
    import java.util.Properties;
    
    public class DBUtil {
    	public Connection getConn() throws IOException, ClassNotFoundException, SQLException{
    		//得到文件路径
    		File file=new File("jdbc.properties");
    		Connection conn=null;
    		//得到输入流
    		InputStream input = new BufferedInputStream(new FileInputStream(file));
    		//得到文件属性
    		Properties p=new Properties();
    		//从输入字符流读取属性列表
    		p.load(input);
    		//关闭输入流
    		input.close();
    		String className=p.getProperty("jdbc.drivers");
    		String url=p.getProperty("url");
    		String user=p.getProperty("username");
    		String password=p.getProperty("password");
    		//注冊载入驱动
    		Class.forName(className);
    		conn=DriverManager.getConnection(url, user, password);
    		return conn;
    	}
    	public void close(Connection conn,PreparedStatement pst,Statement st,ResultSet rs){
    		if(rs!=null){
    			try {
    				rs.close();
    			} catch (SQLException e) {
    				e.printStackTrace();
    			}
    		}
    		if(st!=null){
    			try {
    				st.close();
    			} catch (SQLException e) {
    				e.printStackTrace();
    			}
    		}
    		if(pst!=null){
    			try {
    				pst.close();
    			} catch (SQLException e) {
    				e.printStackTrace();
    			}
    		}
    		if(conn!=null){
    			try {
    				conn.close();
    			} catch (SQLException e) {
    				e.printStackTrace();
    			}
    		}
    	}
    }
    

    获得连接的其它方法:

    1)通过DriverManager类获得连接对象

    方法

    getConnection(String url)

    getConnection(String url, String user, String passwd)

    getConnection(String url, java.util.properties info)

    演示样例

    DriverManager.getConnection(“jdbc:mysql://localhost:3306/test”, “root”,”root”);

    Properties  pro = new  Properties();

    pro.setProperty(“user”,”root”);       //键是user,不是username

    pro.setProperty(“password”,”root”);

    Connection con = DriverManager.getConnection(

    “jdbc:mysql://localhost:3306/test”, pro);

    2)通过指定的驱动对象直接调用connect()方法

    语法
    Connection con = Driver.connect(urlString, properties)

    演示样例

    Driver  drv = new  com.mysql.jdbc.Driver();
    Connection  con = null;  
    Properties  pro = new  Properties();
    pro.setProperty(“user”,”root”);         //键是user,不是username
    pro.setProperty(“password”,”root”);
    try { 
            con = drv.connect(“jdbc:mysql://localhost:3306/test”, pro);
    }catch(SQLException  e){   e.printStackTrace();  }

    -----------------------------------------------------------------------------------------------------------------------------------------------------------------

    Statement相关接口:

    Statement:运行SQL语句,对数据库进行操作

    executeQuery():查询数据

    executeUpdate():加入数据。删除数据。改动数据

    PreparedStatement:扩展Statement接口。对预编译的SQL语句进行处理,提高效率

    CallableStatement:扩展PreparedStatement接口,运行数据库存储过程


    1 Statement对象

    创建Statement

    Statement对象用来运行SQL语句,对数据进行操作

    通过connection.createStatement()方法得到Statement对象

    语法

    Statement  stm = connection.createStatement();

    演示样例

    Statement  stm = null; 

    ResultSet  rs = null;
    try{
     stm = connection.crateStatement();
     rs = stm.executeQuery("select  id, name, age  from  student");
     }catch(SQLException e) {}

    运行SQL语句

    通过Statement对象将SQL语句原样传送到已经建立连接的数据库并运行

    查询数据的SQL语句运行后得到的结果集以表数据的形式存储在java.sql.ResultSet对象中,通过ResultSet对象訪问查询结果

    executeQuery(sqlString):运行查询相关的SQL语句,返回ResultSet对象

    加入,删除,改动数据的SQL语句运行后返回整数。表示受到影响的行数

    executeUpdate(sqlString):运行添加。改动,删除相关SQL语句或不返回不论什么内容的SQL语句

    演示样例
    Statement  stm = con.createStatement();
    ResultSet  rs = stm.executeQuery(“select  *  from  student”);

    Statement  stm = con.createStatement();
    int  count= stm.executeUpdate(“update  student  set  age=25  where  id=1”);


    2 PreparedStatement对象:

    对SQL语句的编译结果在缓存中保留。提高多次运行的效率

    statement每次运行sql语句,相关数据库都要先将sql语句进行编译。然后运行。

    而preparedstatement则将sql语句编译的结果保留,能够多次运行。
    语法
    PreparedStatement pstm = connection.prepareStatement(sqlString);
    演示样例
       String  sql = “select  *  from  student  where  id=?”;
    pstm = connection.prepareStatement(sql);
    pstm.setInt(1, 1);       //setString(),setFloat()
    rs = pstm.executeQuery();              //executeUpdate()
    ……
    pstm.setInt(1, 2);
    rs = pstm.executeQuery();


    3 CallableStatement对象:

    1)运行数据库存储过程(数据库中定义的函数)

    语法

    CallableStatement  cstm = connection.prepareCall(sqlString);

    演示样例

    CallabeStatement  cstm = null;
    try{
       cstm = connection.prepareCall(“{call proc_insert_test(?,?)}”);
       cstm.setString(1, “sunqi”);
       cstm.setInt(2, 33);
       cstm.executeUpdate();
    }catch(SQLException e){}

    2)存储过程返回值

    CallabeStatement  cstm = null;
    try{
       cstm = connection.prepareCall(“{call proc_select_test(?)}”);
       cstm.setInt(1, 30);
       rs = cstm.executeQuery();
    }catch(SQLException e){}

    ----------------------------------------------------------------------------------------------------------------------------------------------------------------


  • 相关阅读:
    android:versionCode和android:versionName 用途
    ProgressDialog使用总结
    对 Android 开发者有益的 40 条优化建议
    Android TextView换行问题
    Android TextView自动换行文字排版参差不齐的原因
    Python 生成requirement 使用requirements.txt
    PLSQL简介
    python魔法方法详解
    深入了解Token认证的来龙去脉
    数组、链表、栈、队列和STL
  • 原文地址:https://www.cnblogs.com/yxysuanfa/p/6918995.html
Copyright © 2011-2022 走看看