打通Java與MySQL的橋樑——jdbc

來源:互聯網
上載者:User

標籤:語句   unicode   cal   har   完整   name   資料庫更新   str   user   

實現的基本步驟:

  1、載入驅動程式:    

Class.forName("com.mysql.jdbc.Driver");

  

  2、獲得資料可串連:  

  private static final String url = "jdbc:mysql://localhost:3306/shopping?useUnicode=true&characterEncoding=UTF-8&useSSL=false"; //資料庫地址  private static final String usename = "root";  private static final String password = "root"; //資料庫密碼  Connection connection = DriverManager.getConnection(URL,USER,PASSWORD); 

  其中,url中jdbc表示串連方式,mysql表示資料庫軟體為mysql,localhost表示資料庫地址,3306表示資料庫連接埠,shopping表示資料庫名稱。

  3、通過資料庫的串連操作資料庫,實現增刪改查  

Statement statement = connection.createStatement();

  

ResultSet  resultSet = statement.executeQuery("SELECT * FROM goods;");  //用於執行資料庫查詢

ResultSet  resultSet = statement.executeUpdate("");//用於執行資料庫更新

  另外一種sql語句執行方法:

PreparedStatement pStatement = connection.prepareStatement("");  //編譯sql代碼pStatement.execute();  //執行sql代碼

  下面是一個完整的測試代碼:

package util;import java.sql.Connection;import java.sql.DriverManager;import java.sql.ResultSet;import java.sql.SQLException;import java.sql.Statement;public class DBHelper {private static String driver = "com.mysql.jdbc.Driver";   //資料庫驅動//串連資料庫的URL地址private static final String url = "jdbc:mysql://localhost:3306/shopping?useUnicode=true&characterEncoding=UTF-8&useSSL=false";private static final String usename = "root";private static final String password = "root"; //資料庫密碼private static Connection connection =null;//靜態代碼塊負責載入驅動static{//靜態塊中的代碼會優先被執行try {Class.forName(driver);} catch (ClassNotFoundException e) {// TODO Auto-generated catch blocke.printStackTrace();}}//單例模式返回資料庫連接對象public static Connection getConnection(){if(connection==null){try {connection = DriverManager.getConnection(url,usename,password);} catch (SQLException e) {// TODO Auto-generated catch blocke.printStackTrace();}return connection;}return connection;}public static void main(String[] args) {ResultSet resultSet = null;try{Connection connection = DBHelper.getConnection();Statement statement =  connection.createStatement(); resultSet = statement.executeQuery("SELECT * FROM goods;");  while(resultSet.next()){System.out.println(resultSet.getString("name")); }}catch(Exception e){e.printStackTrace();}}}

  

  

打通Java與MySQL的橋樑——jdbc

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.