最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

JDBC插入數(shù)據(jù)返回數(shù)據(jù)主鍵代碼實例

 更新時間:2020年11月04日 09:54:41   作者:cuisuqiang  
這篇文章主要介紹了JDBC插入數(shù)據(jù)返回數(shù)據(jù)主鍵代碼實例,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下

Java數(shù)據(jù)庫連接,(Java Database Connectivity,簡稱JDBC)是Java語言中用來規(guī)范客戶端程序如何來訪問數(shù)據(jù)庫的應用程序接口,提供了諸如查詢和更新數(shù)據(jù)庫中數(shù)據(jù)的方法。JDBC也是Sun Microsystems的商標。我們通常說的JDBC是面向關系型數(shù)據(jù)庫的。

代碼如下

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;
/**
 * 數(shù)據(jù)庫連接對象管理類
 * @說明
 * @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); 
      // 如果使用靜態(tài)的SQL,則不需要動態(tài)插入?yún)?shù)
      pstmt.setString(1, new Date().toLocaleString());
      pstmt.executeUpdate(); 
      // 檢索由于執(zhí)行此 Statement 對象而創(chuàng)建的所有自動生成的鍵 
      ResultSet rs = pstmt.getGeneratedKeys(); 
      if (rs.next()) {
        Long id = rs.getLong(1); 
        System.out.println("數(shù)據(jù)主鍵:" + 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;
	}
}

打印生成的主鍵:

數(shù)據(jù)主鍵:25

以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。

相關文章

最新評論

湖州市| 绵竹市| 八宿县| 收藏| 万全县| 石阡县| 吉林省| 丰都县| 阿城市| 钦州市| 扎赉特旗| 全南县| 庄浪县| 蚌埠市| 清原| 平远县| 乌鲁木齐县| 连江县| 株洲县| 三亚市| 察隅县| 沙湾县| 融水| 云梦县| 芮城县| 沛县| 富蕴县| 弋阳县| 介休市| 东方市| 城步| 监利县| 青河县| 寿光市| 格尔木市| 彰化市| 永兴县| 山阳县| 紫阳县| 苏尼特左旗| 临夏市|