標籤:
不多說,直接上代碼。百度上面也是一大堆,大家多問百度就行。
在利用JDBC訪問資料庫過程中,主要涉及三種資源:對資料庫的串連的連線物件Connection,SQL語句對象 Statement,訪問結果集ResultSet 或 RowSet。
package ShopCar;import java.sql.Connection;import java.sql.DriverManager;import java.sql.ResultSet;import java.sql.SQLException;import java.sql.Statement;public class JDBCTest { public static void main(String[] args) { //驅動程式 String driver = "com.mysql.jdbc.Driver"; String url = "jdbc:mysql://127.0.0.1:3306/db"; String user = "root"; String password = ""; try { Class.forName(driver);//載入驅動 Connection conn = DriverManager.getConnection(url,user,password); // 串連URL為 jdbc:mysql://伺服器位址/資料庫名 ,後面的2個參數分別是登陸使用者名稱和密碼 System.out.println("Success connect Mysql server!"); // statement用來執行SQL語句 Statement stmt = conn.createStatement(); // 結果集 ResultSet rs = stmt.executeQuery("select * from `student`"); // student 為你表的名稱 while (rs.next()) { System.out.println(rs.getString("Sno")); } } catch (Exception e) { // TODO: handle exception System.out.print("get data error!"); e.printStackTrace(); } }}
如何向資料庫中插入資料
import java.sql.*;publicclass Myjproject { publicstaticvoid main(String args[]) { try { Class.forName("com.mysql.jdbc.Driver"); //載入MYSQL JDBC驅動程式 //Class.forName("org.gjt.mm.mysql.Driver"); System.out.println("Success loading Mysql Driver!"); } catch (Exception e) { System.out.print("Error loading Mysql Driver!"); e.printStackTrace(); } try { Connection connect = DriverManager.getConnection( "jdbc:mysql://localhost:3306/test","root","123456"); int num=100; PreparedStatement Statement=connect.prepareStatement("INSERT INTO user VALUES(?,?)"); for(int i=0;i<num;i++) //定義個100次的迴圈,往表裡插入一百條資訊。 { Statement.setString(1,"chongshi"+i); Statement.setString(2,"bo"+i); Statement.executeUpdate(); } // } catch (ClassNotFoundException e) { // TODO Auto-generated catch block // System.out.println("An error has occurred:"+e.toString()); // e.printStackTrace(); }catch(SQLException e) { } }}
jsp 配置MySQL伺服器 以及資料的插入和讀取