ResultSet rs=sql.executeQueryjava
Example11_1mysql
import java.sql.*; public class Example11_1 { public static void main(String args[]) { Connection con=null; Statement sql; ResultSet rs; try{ Class.forName("com.mysql.jdbc.Driver"); //加載JDBC_MySQL驅動 } catch(Exception e){} String uri = "jdbc:mysql://localhost:3306/students?useSSL=true"; String user ="root"; String password =""; try{ con = DriverManager.getConnection(uri,user,password); //鏈接代碼 } catch(SQLException e){ } try { sql=con.createStatement(); rs=sql.executeQuery("SELECT * FROM mess"); //查詢mess表 while(rs.next()) {//當存在下一個數據是返回true String number=rs.getString(1);//將表第一列的數據傳給number String name=rs.getString(2); Date date=rs.getDate(3); float height=rs.getFloat(4); System.out.printf("%s\t",number); System.out.printf("%s\t",name); System.out.printf("%s\t",date); System.out.printf("%.2f\n",height); } con.close();//關閉鏈接 } catch(SQLException e) { System.out.println(e); } } }
這個代碼是用來查詢student數據庫中的mess表的所有記錄sql
Example11_2數據庫
import java.sql.*; public class Example11_2 { public static void main(String args[]) { Connection con; Statement sql; ResultSet rs; con = GetDBConnection.connectDB("students","root",""); if(con == null ) return; try { sql=con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY); rs = sql.executeQuery("SELECT * FROM mess "); rs.last(); int max = rs.getRow(); System.out.println("表共有"+max+"條記錄,隨機抽取2條記錄:"); int [] a =GetRandomNumber.getRandomNumber(max,2);//獲得1-max之間2個不一樣隨機數 for(int i:a){ rs.absolute(i);//油標移動到第i行 String number = rs.getString(1); String name = rs.getString(2); Date date = rs.getDate(3); float h = rs.getFloat(4); System.out.printf("%s\t",number); System.out.printf("%s\t",name); System.out.printf("%s\t",date); System.out.printf("%.2f\n",h); } con.close(); } catch(SQLException e) { System.out.println(e); } } } import java.sql.*; public class GetDBConnection { public static Connection connectDB(String DBName,String id,String p) { Connection con = null; String uri = "jdbc:mysql://localhost:3306/"+DBName+"?useSSL=true&characterEncoding=utf-8"; try{ Class.forName("com.mysql.jdbc.Driver");//加載JDBC-MySQL驅動 } catch(Exception e){} try{ con = DriverManager.getConnection(uri,id,p); //鏈接代碼 } catch(SQLException e){} return con; } } import java.util.*; public class GetRandomNumber { public static int [] getRandomNumber(int max,int amount) { //1-max之間的amount個不一樣隨機整數 int [] randomNumber = new int[amount]; int index =0; randomNumber[0]= -1; Random random = new Random(); while(index<amount){ int number = random.nextInt(max)+1; boolean isInArrays=false; for(int m:randomNumber){//m依次取數組randomNumber元素的值(見3.7) if(m == number) isInArrays=true; //number在數組裏了 } if(isInArrays==false){ //若是number不在數組randomNumber中: randomNumber[index] = number; index++; } } return randomNumber; } }
將數據庫單獨分裝在一個GetDatabaseConnection類中。隨機查詢student數據庫中的mess表的兩條記錄。apache
Example11_3編程
import java.sql.*; public class Example11_3 { public static void main(String args[]) { Connection con; Statement sql; ResultSet rs; con = GetDBConnection.connectDB("students","root",""); if(con == null ) return; String c1=" year(birthday)<=2000 and month(birthday)>7";//條件1 String c2=" name Like '張_%'"; String c3=" height >1.65"; String sqlStr = "select * from mess where "+c1+" and "+c2+" and "+c3+"order by birthday"; try { sql=con.createStatement(); rs = sql.executeQuery(sqlStr); while(rs.next()) { String number=rs.getString(1); String name=rs.getString(2); Date date=rs.getDate(3); float height=rs.getFloat(4); System.out.printf("%s\t",number); System.out.printf("%s\t",name); System.out.printf("%s\t",date); System.out.printf("%.2f\n",height); } con.close(); } catch(SQLException e) { System.out.println(e); } } } import java.sql.*; public class GetDBConnection { public static Connection connectDB(String DBName,String id,String p) { Connection con = null; String uri = "jdbc:mysql://localhost:3306/"+DBName+"?useSSL=true&characterEncoding=utf-8"; try{ Class.forName("com.mysql.jdbc.Driver");//加載JDBC-MySQL驅動 } catch(Exception e){} try{ con = DriverManager.getConnection(uri,id,p); //鏈接代碼 } catch(SQLException e){} return con; } }
這個代碼是查詢mess表中姓張,身高大於16.5,出生年份爲2000或2000年以前,月份在七月份以後的學生,並按出生日期排序。數組
Example11_4dom
import java.sql.*; public class Example11_4 { public static void main(String args[]) { Connection con; Statement sql; ResultSet rs; con = GetDBConnection.connectDB("students","root",""); if(con == null ) return; String jiLu="('R11q','王三','2000-10-23',1.66),"+ "('R10q','李武','1989-10-23',1.76)"; //2條記錄 String sqlStr ="insert into mess values"+jiLu; try { sql=con.createStatement(); int ok = sql.executeUpdate(sqlStr); rs = sql.executeQuery("select * from mess"); while(rs.next()) { String number=rs.getString(1); String name=rs.getString(2); Date date=rs.getDate(3); float height=rs.getFloat(4); System.out.printf("%s\t",number); System.out.printf("%s\t",name); System.out.printf("%s\t",date); System.out.printf("%.2f\n",height); } con.close(); } catch(SQLException e) { System.out.println("記錄中number值不能重複"+e); } } }
這個代碼是在mess表中插入兩條記錄。this
Example11_53d
import java.sql.*; public class Example11_5 { public static void main(String args[]) { Connection con; PreparedStatement preSql; //預處理語句對象preSql ResultSet rs; con = GetDBConnection.connectDB("students","root",""); if(con == null ) return; String sqlStr ="insert into mess values(?,?,?,?)"; try { preSql = con.prepareStatement(sqlStr);//獲得預處理語句對象preSql preSql.setString(1,"A001"); //設置第1個?表明的值 preSql.setString(2,"劉偉"); //設置第2個?表明的值 preSql.setString(3,"1999-9-10"); //設置第3個?表明的值 preSql.setFloat(4,1.77f); //設置第4個?表明的值 int ok = preSql.executeUpdate(); sqlStr="select * from mess where name like ? "; preSql = con.prepareStatement(sqlStr);//獲得預處理語句對象preSql preSql.setString(1,"張%"); //設置第1個?表明的值 rs = preSql.executeQuery(); while(rs.next()) { String number=rs.getString(1); String name=rs.getString(2); Date date=rs.getDate(3); float height=rs.getFloat(4); System.out.printf("%s\t",number); System.out.printf("%s\t",name); System.out.printf("%s\t",date); System.out.printf("%.2f\n",height); } con.close(); } catch(SQLException e) { System.out.println("記錄中number值不能重複"+e); } } } import java.sql.*; public class GetDBConnection { public static Connection connectDB(String DBName,String id,String p) { Connection con = null; String uri = "jdbc:mysql://localhost:3306/"+DBName+"?useSSL=true&characterEncoding=utf-8"; try{ Class.forName("com.mysql.jdbc.Driver");//加載JDBC-MySQL驅動 } catch(Exception e){} try{ con = DriverManager.getConnection(uri,id,p); //鏈接代碼 } catch(SQLException e){} return con; } }
此代碼是使用預處理語句向mess表添加並查詢了姓張的記錄
Example11_6
import javax.swing.*; public class Example11_6 { public static void main(String args[]) { String [] tableHead; String [][] content; JTable table ; JFrame win= new JFrame(); Query findRecord = new Query(); findRecord.setDatabaseName("students"); findRecord.setSQL("select * from mess"); content = findRecord.getRecord(); tableHead=findRecord.getColumnName(); table = new JTable(content,tableHead); win.add(new JScrollPane(table)); win.setBounds(12,100,400,200); win.setVisible(true); win.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } } import java.sql.*; public class Query { String databaseName=""; //數據庫名 String SQL; //SQL語句 String [] columnName; //所有字段(列)名 String [][] record; //查詢到的記錄 public Query() { try{ Class.forName("com.mysql.jdbc.Driver");//加載JDBC-MySQL驅動 } catch(Exception e){} } public void setDatabaseName(String s) { databaseName=s.trim(); } public void setSQL(String SQL) { this.SQL=SQL.trim(); } public String[] getColumnName() { if(columnName ==null ){ System.out.println("先查詢記錄"); return null; } return columnName; } public String[][] getRecord() { startQuery(); return record; } private void startQuery() { Connection con; Statement sql; ResultSet rs; String uri = "jdbc:mysql://localhost:3306/"+ databaseName+"?useSSL=true&characterEncoding=utf-8"; try { con=DriverManager.getConnection(uri,"root",""); sql=con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY); rs=sql.executeQuery(SQL); ResultSetMetaData metaData = rs.getMetaData(); int columnCount = metaData.getColumnCount();//字段數目 columnName=new String[columnCount]; for(int i=1;i<=columnCount;i++){ columnName[i-1]=metaData.getColumnName(i); } rs.last(); int recordAmount =rs.getRow(); //結果集中的記錄數目 record = new String[recordAmount][columnCount]; int i=0; rs.beforeFirst(); while(rs.next()) { for(int j=1;j<=columnCount;j++){ record[i][j-1]=rs.getString(j); //第i條記錄,放入二維數組的第i行 } i++; } con.close(); } catch(SQLException e) { System.out.println("請輸入正確的表名"+e); } } }
這段代碼的功能是將數據庫名以及SQL語句傳遞給Query類的對象。
Example11_7
import java.sql.*; public class Example11_7{ public static void main(String args[]){ Connection con = null; Statement sql; ResultSet rs; String sqlStr; con = GetDBConnection.connectDB("students","root",""); if(con == null ) return; try{ float n = 0.02f; con.setAutoCommit(false); //關閉自動提交模式 sql = con.createStatement(); sqlStr = "select name,height from mess where number='R1001'"; rs = sql.executeQuery(sqlStr); rs.next(); float h1 = rs.getFloat(2); System.out.println("事務以前"+rs.getString(1)+"身高:"+h1); sqlStr = "select name,height from mess where number='R1002'"; rs = sql.executeQuery(sqlStr); rs.next(); float h2 = rs.getFloat(2); System.out.println("事務以前"+rs.getString(1)+"身高:"+h2); h1 = h1-n; h2 = h2+n; sqlStr = "update mess set height ="+h1+" where number='R1001'"; sql.executeUpdate(sqlStr); sqlStr = "update mess set height ="+h2+" where number='R1002'"; sql.executeUpdate(sqlStr); con.commit(); //開始事務處理,若是發生異常直接執行catch塊 con.setAutoCommit(true); //恢復自動提交模式 String s = "select name,height from mess"+ " where number='R1001'or number='R1002'"; rs = sql.executeQuery(s); while(rs.next()){ System.out.println("事務後"+rs.getString(1)+ "身高:"+rs.getFloat(2)); } con.close(); } catch(SQLException e){ try{ con.rollback(); //撤銷事務所作的操做 } catch(SQLException exp){} } } } import java.sql.*; public class GetDBConnection { public static Connection connectDB(String DBName,String id,String p) { Connection con = null; String uri = "jdbc:mysql://localhost:3306/"+DBName+"?useSSL=true&characterEncoding=utf-8"; try{ Class.forName("com.mysql.jdbc.Driver");//加載JDBC-MySQL驅動 } catch(Exception e){} try{ con = DriverManager.getConnection(uri,id,p); //鏈接代碼 } catch(SQLException e){} return con; } }
這段代碼的功能是將mess表中的number字段R1001的height值減小n,並將減小的n增長到字段是R1002的height上。
Example11_8
import java.sql.*; public class Example11_8 { public static void main(String[] args) { Connection con =null; Statement sta = null; ResultSet rs; String SQL; try { Class.forName("org.apache.derby.jdbc.EmbeddedDriver");//加載驅動 } catch(Exception e) { System.out.println(e); return; } try { String uri ="jdbc:derby:students;create=true"; con=DriverManager.getConnection(uri); //鏈接數據庫 sta = con.createStatement(); } catch(Exception e) { System.out.println(e); return; } try { SQL = "create table chengji(name varchar(40),score float)"; sta.execute(SQL);//建立表 } catch(SQLException e) { //System.out.println("該表已經存在"); } SQL ="insert into chengji values"+ "('張三', 90),('李斯', 88),('劉二', 67)"; try { sta.execute(SQL); rs = sta.executeQuery("select * from chengji "); // 查詢表中的記錄 while(rs.next()) { String name=rs.getString(1); System.out.print(name+"\t"); float score=rs.getFloat(2); System.out.println(score); } con.close(); } catch(SQLException e) { System.out.println(e); } } }
這段代碼的功能是使用了Derby數據庫系統建立了名字是student的數據庫,並在數據庫中創建了chengji表
習題11編程題
第一題
import java.sql.*; public class test1 { public static void main(String args[]) { Connection con; Statement sql; ResultSet rs; con = GetDBConnection.connectDB("students","root","");//鏈接數據庫 if(con == null ) return; String sqlStr = "select * from mess "+"order by birthday"; //經過order by排序 try { sql=con.createStatement(); rs = sql.executeQuery(sqlStr); while(rs.next()) { String number=rs.getString(1); String name=rs.getString(2); Date date=rs.getDate(3); float height=rs.getFloat(4); System.out.printf("%s\t",number); System.out.printf("%s\t",name); System.out.printf("%s\t",date); System.out.printf("%.2f\n",height); } con.close(); } catch(SQLException e) { System.out.println(e); } } }
GetDBConnection 類
import java.sql.*; public class GetDBConnection { public static Connection connectDB(String DBName,String id,String p) { Connection con = null; String uri = "jdbc:mysql://localhost:3306/"+DBName+"?useSSL=true&characterEncoding=utf-8"; try{ Class.forName("com.mysql.jdbc.Driver");//加載JDBC-MySQL驅動 } catch(Exception e){} try{ con = DriverManager.getConnection(uri,id,p); //鏈接代碼 } catch(SQLException e){} return con; } }
第二題
import java.sql.*; public class Query { String databaseName=""; //數據庫名 String SQL; //SQL語句 String [] columnName; //所有字段(列)名 String [][] record; //查詢到的記錄 public Query() { try{ Class.forName("com.mysql.jdbc.Driver");//加載JDBC-MySQL驅動 } catch(Exception e){} } public void setDatabaseName(String s) { databaseName=s.trim(); } public void setSQL(String SQL) { this.SQL=SQL.trim(); } public String[] getColumnName() { if(columnName ==null ){ System.out.println("先查詢記錄"); return null; } return columnName; } public String[][] getRecord() { startQuery(); return record; } private void startQuery() { Connection con; Statement sql; ResultSet rs; String uri = "jdbc:mysql://localhost:3306/"+ databaseName+"?useSSL=true&characterEncoding=utf-8"; try { con=DriverManager.getConnection(uri,"root",""); sql=con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY); rs=sql.executeQuery(SQL); ResultSetMetaData metaData = rs.getMetaData(); int columnCount = metaData.getColumnCount();//字段數目 columnName=new String[columnCount]; for(int i=1;i<=columnCount;i++){ columnName[i-1]=metaData.getColumnName(i); } rs.last(); int recordAmount =rs.getRow(); //結果集中的記錄數目 record = new String[recordAmount][columnCount]; int i=0; rs.beforeFirst(); while(rs.next()) { for(int j=1;j<=columnCount;j++){ record[i][j-1]=rs.getString(j); //第i條記錄,放入二維數組的第i行 } i++; } con.close(); } catch(SQLException e) { System.out.println("請輸入正確的表名"+e); } } }
Query類
import javax.management.Query; import javax.swing.*; public class test2 { public static void main (String args[]) { String [] tableHead; String [] content; JTable table; JFrame win= new JFrame(); Query findRecord = new Query(); findRecord.setDatabaseName(args[0]); findRecord.setSQL("select * from "+args[1]); content = findRecord.getRecord(); tableHead=findRecord.getColumnName(); table = new JTable(content,tableHead); win.add(new JScrollPane(table)); win.setBounds(12,100,400,200); win.setVisible(true); win.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } }