• JAVA 数据库编程(1)


     JDBC驱动程序类型

    1)驱动程序将JDBC翻译成ODBC,然后使用一个ODBC驱动程序与数据库进行通信.

    2)驱动程序是由部分JAVA程序和部分本地代码组成,用于与数据库的客户端API进行通信.

    3)驱动程序是纯JAVA客户端类库,它使用一种与具体数据库无关的协议将数据库请求发送给服务端构件,然后该构件再将数据库请求翻译成特定的数据库协议.

    4)驱动程序是纯JAVA类库,它将JDBC请求直接翻译成特定的数据库协议.

    注册驱动器类

     1)JAVA程序中加载驱动器类

    Class.forName("org.postgresql.Driver");//不同数据库不同JDBC驱动器类.

     2)设置jdbc.drivers属性.可以用命令行参数指定.

    java -Djdbc.drivers=org.postgresql.Driver ProgramName

    或者在应用中用下面这样的调用来设置系统属性

    System.setProperty("jdbc.drivers","org.postgresql.Driver");

    连接到数据库

    在Java程序中,我们可以在代码中打开一个数据库连接,例如

    String url="jdbc:postgresql:corejava";

    String username=""dbuser;

    String password="secret";

    Connection conn=DriverManager.getConnection(url,username,password);

    执行SQL语句

    在执行SQL命令之前,首先需要创建一个Statement对象.要创建statement对象,需要使用调用DriverManager.getConnection方法所获得的Connection对象.

    Statement stat=conn.createStatement();//用于执行不带参数的SQL查询和更新.

    接着,将要执行的SQL语句放入字符串中

    String command="update..."

    然后调用statement类中的executeUpdate方法:

    stat.executeUpdate(command);//返回影响行数,executeUpdate可用于执行Insert,update,delete,create table,drop之类语句

    执行select查询时必须使用executeQuery方法,另外还有一个execute方法可以执行任意SQL语句,此方法通常只用于用户提供的交互式查询.

    通常执行查询语句,更感兴趣的是查询结果.executeQuery方法返回一个ResultSet对象,可以通过它来每次一行地迭代遍历所有查询结果.

    注:每个Connection对象都可以创建一个或一个以上的Statement对象.同一个Statement对象可以用于多个不相关的命令和查询.但是,一个Statement对象最多只能打开一个结果集.如果需要执行多个查询操作,且需要同时分析查询结果,那么必须创建多个Statement对象.

    获取JDBC驱动程序同时支持的对象Statement总数 DatabaseMetaDate.getMaxStatements();

    当使用完ResultSet,Statement或Connection对象时,应立即调用close方法.这些对象都使用了规模较大的数据结构,所以我们不应该等待垃圾回收器来处理它们.

     

    ResultSet rs = stat.executeQuery("select * from books");
    while(rs.next)
    {
         System.out.println(rs.getString(列名));
    }
    import java.sql.*;
    import java.io.*;
    import java.util.*;
    
    
    public class TestDB {
    
     /**
      * @param args
      */
     public static void main(String[] args) {
      // TODO Auto-generated method stub
      try{
       runTest();
      }
      catch(SQLException ex){
       for(Throwable t:ex)
        t.printStackTrace();
      }
      catch(IOException ex){
       ex.printStackTrace();
      }
     }
     
     public static void runTest() throws SQLException,IOException{
      Connection conn=getConnection();
      try{
       Statement stat = conn.createStatement();
       stat.executeUpdate("create table Greetings (Message char(20))");
       stat.executeUpdate("Insert into Greetings values('Hello,World!!!')");
       
       ResultSet result=stat.executeQuery("select * from Greetings");
       if(result.next())
       {
        System.out.println(result.getString(1));
       }
       result.close();
       stat.executeUpdate("drop table Greetings");
      }finally
      {
       conn.close();
      }
     }
     
     public static Connection getConnection() throws SQLException, IOException{
      Properties props=new Properties();
      FileInputStream in = new FileInputStream("E:\\JAVA_workspace\\JDBC\\src\\database.properties");
      props.load(in);
      in.close();
      
      String drivers=props.getProperty("jdbc.drivers");
      if(drivers!=null)
       System.setProperty("jdbc.drivers", drivers);
      //这样就把第一个参数设置成为系统的全局变量!可以在项目的任何一个地方 通过System.getProperty("变量");来获得
      String ulr=props.getProperty("jdbc.url");
      String username=props.getProperty("jdbc.username");
      String password=props.getProperty("jdbc.password");
      
      
      return DriverManager.getConnection(ulr,username,password);
     }
    }
    
     
    import java.sql.*;
    import java.io.*;
    import java.util.*;
    
    public class ExecSQL {
    
        /**
         * @param args
         */
        public static void main(String[] args) {
            // TODO Auto-generated method stub
            try{
                Scanner in;
                
                if(args.length==0){
                    in=new Scanner(System.in);
                }
                else{
                    in=new Scanner(new File(args[0]));
                }
                
                Connection conn=getConnection();
                try{
                    Statement stat= conn.createStatement();
                    while(true){
                        if(args.length==0) System.out.println("Enter command or EXIT to exit");
                        
                        if(!in.hasNextLine())return;
                        
                        String line = in.nextLine();
                        System.out.println(line);
                        if(line.equalsIgnoreCase("EXIT")) return;
                        if(line.trim().endsWith(";")){
                            line=line.trim();
                            line=line.substring(0,line.length()-1);
                        }
                        try{
                            boolean hasResultSet=stat.execute(line);
                            if(hasResultSet) showResultSet(stat);
                        }
                        catch(SQLException ex){
                            for(Throwable e:ex)
                                e.printStackTrace();
                        }
                    }
                }    
                finally
                {
                    conn.close();
                
                }
                    
            }
            catch(SQLException ex)
            {
                for(Throwable t:ex)
                    t.printStackTrace();
            }
            catch(IOException ex)
            {
                ex.printStackTrace();
            }
            
        }
        
        
        public static Connection getConnection() throws SQLException,IOException    {
            Properties props=new Properties();
            FileInputStream in = new FileInputStream("E:\\JAVA_workspace\\JDBC\\src\\database.properties");
            props.load(in);
            in.close();
            
            String Drivers= props.getProperty("jdbc.drivers");
            if(Drivers !=null) System.setProperty("jdbc.drivers", Drivers);
            String url=props.getProperty("jdbc.url");
            String username=props.getProperty("jdbc.username");
            String password=props.getProperty("jdbc.password");
            
            return DriverManager.getConnection(url,username,password);
        }
        
        public static void showResultSet(Statement stat) throws SQLException{
            ResultSet result=stat.getResultSet();
            ResultSetMetaData metaData=result.getMetaData();
            int columnCount=metaData.getColumnCount();
            
            for(int i = 0;i<=columnCount;i++){
                if(i>1) System.out.print(",");
                System.out.print(metaData.getColumnLabel(i));
            }
            System.out.println();
            
            while(result.next()){
                for(int i=1;i<=columnCount;i++){
                    if(i>1)System.out.print(",");
                    System.out.print(result.getString(i));
                }
                System.out.println();
            }
            result.close();
        }
    }
  • 相关阅读:
    Leetcode 515. Find Largest Value in Each Tree Row
    Paypal2017实习生-软件开发-B卷
    Codeblocks 遇到的问题 Cannot open output file, permission denied
    itoa()函数和atoi()函数详解
    Windows下如何更新 CodeBlocks 中的 MinGW 使其支持新版本 C++
    Leetcode 179. Largest Number
    合并两个有序数组到其中一个数组中
    腾讯2017实习生招聘软件开发编程题
    [LeetCode] 56
    360笔试
  • 原文地址:https://www.cnblogs.com/zhuangjb/p/3122775.html
Copyright © 2020-2023  润新知