JDBC插入資料返回資料主鍵程式碼例項
阿新 • • 發佈:2020-11-05
Java資料庫連線,(Java Database Connectivity,簡稱JDBC)是Java語言中用來規範客戶端程式如何來訪問資料庫的應用程式介面,提供了諸如查詢和更新資料庫中資料的方法。JDBC也是Sun Microsystems的商標。我們通常說的JDBC是面向關係型資料庫的。
程式碼如下
package com.test; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.Statement; import java.util.Date; import java.util.Properties; /** * 資料庫連線物件管理類 * @說明 * @author cuisuqiang * @version 1.0 * @since */ public class ConnectionManager { private static final String url = "jdbc:mysql://localhost:3306/test"; private static final String username = "root"; private static final String userpass = "root"; @SuppressWarnings("deprecation") public static void main(String[] args) throws Exception{ Connection conn = getConnection(); if (null != conn) { String sql = "insert into common_user (name) values(?)"; // 指定返回生成的主鍵 PreparedStatement pstmt = conn.prepareStatement(sql,Statement.RETURN_GENERATED_KEYS); // 如果使用靜態的SQL,則不需要動態插入引數 pstmt.setString(1,new Date().toLocaleString()); pstmt.executeUpdate(); // 檢索由於執行此 Statement 物件而建立的所有自動生成的鍵 ResultSet rs = pstmt.getGeneratedKeys(); if (rs.next()) { Long id = rs.getLong(1); System.out.println("資料主鍵:" + id); } } } public static Connection getConnection() { Connection conn = null; try { com.mysql.jdbc.Driver driver = new com.mysql.jdbc.Driver(); Properties properties = new Properties(); properties.put("user",username); properties.put("password",userpass); conn = driver.connect(url,properties); } catch (Exception e) { e.printStackTrace(); } return conn; } }
列印生成的主鍵:
資料主鍵:25
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。