* Connection : 連接數據庫并擔任傳送數據的任務* Statement : 執行SQL語句* ResultSet :保存Statement執行后產生的查詢結果1.注冊驅動Class.forName(JDBC驅動類);2.獲取數據庫連接Connection con=DriverManager.getConnection(JDBC url,數據庫用戶名,密碼);3.獲得 Statement對象Statement stmt=con.createStatement();4.執行SQL語句ResultSet rs=stmt.executeQuery(select a,b from table);5.處理執行結果while(rs.next()){ int x=rs.getInt("a"); String s=rs.getString("b"); *數據類型要相匹配}6.釋放資源1.rs.close();2.stmt.close();3.con.close();*順序倒過來依次關閉實例:Java使用PReparedStatement接口插入數據庫信息public class PreparedStatementDemo01 { public static final String DBDRIVER = "org.gjt.mm.MySQL.Driver"; public static final String DBURL = "jdbc:mysql://localhost:3306/"; public static final String DBUSER = "root"; public static final String DBPASS = "root"; public static void main(String args[]) throws ParseException, ClassNotFoundException, SQLException { Connection conn = null; //數據庫連接 PreparedStatement pstmt = null; //數據庫操作 Statement stmt = null; ResultSet rs = null; //Rs接口 String name = "黃鵬"; String passWord = "1598741"; int age = 21; String sex = "男"; String birthday ="1992-04-30"; Date temp = null; temp = new SimpleDateFormat("yyyy-MM-dd").parse(birthday); java.sql.Date bri = new java.sql.Date(temp.getTime()); //創建數據庫操作語句 String sql1 = "CREATE DATABASE MyDemo;"; //選擇使用哪個數據庫的語句 String sql2 = "USE MyDemo;"; //創建數據庫表操作語句 String sql3 = "CREATE TABLE user(name varchar(20) primary key,password varchar(20),age int,sex varchar(10),birthday Date);"; //查詢數據庫語句 String sql5 = "select * from user;"; //用PreparedStatement執行的插入語句 String sql4 = "INSERT INTO user(name,password,age,sex,birthday) VALUES(?,?,?,?,?);"; //加載驅動程序 Class.forName(DBDRIVER); //連接mysql數據庫 conn = DriverManager.getConnection(DBURL,DBUSER,DBPASS); //實例化PreparedStatement pstmt = conn.prepareStatement(sql4); //設置第一個?內容 pstmt.setString(1, name); //設置第二個?內容 pstmt.setString(2, password); //設置第三個?內容 pstmt.setInt(3, age); //設置第四個?內容 pstmt.setString(4,sex); //設置第五個?內容 pstmt.setDate(5, bri); //執行數據庫更新,不需要sql stmt = conn.createStatement(); stmt.execute(sql1); stmt.execute(sql2); stmt.execute(sql3); pstmt.executeUpdate(); rs = stmt.executeQuery(sql5); //向控制臺輸出信息 while(rs.next()) { String QueryName = rs.getString("name"); String QueryPwd = rs.getString("password"); int QueryAge = rs.getInt("age"); String QuerySex = rs.getString("sex"); Date QueryDate = rs.getDate("birthday"); System.out.println("name:"+QueryName+" pwd:"+QueryPwd+" "+QueryAge+" sex:"+QueryPwd+" date:"+QueryDate); } pstmt.close(); conn.close(); }}
新聞熱點
疑難解答
圖片精選