標籤:
* 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(); }}
java串連資料庫步驟