jsp 配置MySQL伺服器 以及資料的插入和讀取

來源:互聯網
上載者:User

標籤:

不多說,直接上代碼。百度上面也是一大堆,大家多問百度就行。

在利用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伺服器 以及資料的插入和讀取

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.