国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

Home Database Mysql Tutorial JDBC編程理論知識(1)

JDBC編程理論知識(1)

Jun 07, 2016 pm 03:59 PM
jdbc company database theory Knowledge programming

1.SUN公司為統(tǒng)一對數(shù)據(jù)庫的操作,定義了一套Java操作數(shù)據(jù)庫的規(guī)范,稱之為JDBC 2.JDBC全稱為:Java Data Base Connectivity(java數(shù)據(jù)庫連接),它主要由接口組成。 組成JDBC的2個包: (1)java.sql.*; (2)javax.sql.*; 3.JDBC在程序中的位置: 4.JDBC的

1.SUN公司為統(tǒng)一對數(shù)據(jù)庫的操作,定義了一套Java操作數(shù)據(jù)庫的規(guī)范,稱之為JDBC

2.JDBC全稱為:Java Data Base Connectivity(java數(shù)據(jù)庫連接),它主要由接口組成。
組成JDBC的2個包:
?。?)java.sql.*;
 (2)javax.sql.*;

3.JDBC在程序中的位置:
\

4.JDBC的六個固定步驟
1,注冊數(shù)據(jù)庫驅(qū)動[利用反射]
2,取得數(shù)據(jù)庫連接對象Connection
3,創(chuàng)建SQL對象
4,執(zhí)行SQL命令,并返回結(jié)果集
5,處理結(jié)果集
6,依次關(guān)閉結(jié)果集

5.JDBC的DriverManager對象:

(1).Jdbc程序中的DriverManager用于加載驅(qū)動,并創(chuàng)建與數(shù)據(jù)庫的鏈接,這個API的常用方法:DriverManager.registerDriver(new Driver()),注意:在實際開發(fā)中,并不推薦采用這個方法注冊驅(qū)動。查看Driver的源代碼可以看到,如果采用此種方式,會導(dǎo)致驅(qū)動程序加載兩次,也就是在內(nèi)存中會有兩個Driver對象。

java.sql.Driver(接口)-com.mysql.jdbc.Driver(實現(xiàn)類)
(首先返回true)boolean acceptsURL(String url)
查詢驅(qū)動程序是否認(rèn)為它可以打開到給定 URL 的連接。
(然后)Connection connect(String url, Properties info)
試圖創(chuàng)建一個到給定 URL 的數(shù)據(jù)庫連接。

(2).推薦方式:Class.forName(“com.mysql.jdbc.Driver”);采用此種方式不會導(dǎo)致驅(qū)動對象在內(nèi)存中重復(fù)出現(xiàn),并且采用此種方式,程序僅僅只需要一個字符串,不需要import驅(qū)動的API,這樣可使程序不依賴具體的驅(qū)動,使程序的靈活性更高。
DriverManager.getConnection(url, user, password),根據(jù)url獲取數(shù)據(jù)庫的鏈接。

6.數(shù)據(jù)庫的URL

URL用于標(biāo)識數(shù)據(jù)庫的位置,程序員通過URL地址告訴JDBC程序連接哪個數(shù)據(jù)庫,

(1).常用數(shù)據(jù)庫URL地址的寫法:
Oracle—jdbc:oracle:thin:@localhost:1521:sid
SqlServer—jdbc:microsoft:sqlserver://localhost:1433; DatabaseName=sid
MySql—jdbc:mysql://localhost:3306/sid
(2).Mysql的url地址的簡寫形式: jdbc:mysql:///sid

7.JDBC的Connection對象:

Jdbc程序中的Connection,它用于代表數(shù)據(jù)庫的鏈接,Collection是數(shù)據(jù)庫編程中最重要的一個對象,客戶端與數(shù)據(jù)庫所有交互都是通過connection對象完成的,這個對象的常用方法:
createStatement():創(chuàng)建向數(shù)據(jù)庫發(fā)送sql的statement對象。
prepareStatement(sql) :創(chuàng)建向數(shù)據(jù)庫發(fā)送預(yù)編譯sql的PrepareSatement對象。
prepareCall(sql):創(chuàng)建執(zhí)行存儲過程的callableStatement對象。
setAutoCommit(boolean autoCommit):設(shè)置事務(wù)是否自動提交。
commit() :在鏈接上提交事務(wù)。
rollback() :在此鏈接上回滾事務(wù)。

8.JDBC的statement:

Jdbc程序中的Statement對象用于向數(shù)據(jù)庫發(fā)送SQL語句, Statement對象常用方法:
execute(String sql):用于向數(shù)據(jù)庫發(fā)送任意sql語句
executeQuery(String sql) :只能向數(shù)據(jù)發(fā)送select語句。
executeUpdate(String sql):只能向數(shù)據(jù)庫發(fā)送insert、update或delete語句
addBatch(String sql) :把多條sql語句放到一個批處理中。
executeBatch():向數(shù)據(jù)庫發(fā)送一批sql語句執(zhí)行。
clearBatch():清空緩沖

9.JDBC的ResultSet對象:

Jdbc程序中的ResultSet用于代表Sql語句的執(zhí)行結(jié)果。Resultset封裝執(zhí)行結(jié)果時,采用的類似于表格的方式。ResultSet 對象維護(hù)了一個指向表格數(shù)據(jù)行的游標(biāo),初始的時候,游標(biāo)在第一行之前,調(diào)用ResultSet.next() 方法,可以使游標(biāo)指向具體的數(shù)據(jù)行,進(jìn)行調(diào)用方法獲取該行的數(shù)據(jù)。
(1)ResultSet既然用于封裝執(zhí)行結(jié)果的,所以該對象提供的都是用于獲取數(shù)據(jù)的get方法:
獲取任意類型的數(shù)據(jù)
getObject(int index)
getObject(string columnName)
獲取指定類型的數(shù)據(jù),例如:
getString(int index)
getString(String columnName)

(2).ResultSet還提供了對結(jié)果集進(jìn)行滾動的方法:
next():移動到下一行
previous():移動到前一行
absolute(int row):移動到指定行
beforeFirst():移動resultSet的最前面。
afterLast() :移動到resultSet的最后面。

10.MySQL和java的數(shù)據(jù)類型的轉(zhuǎn)換

\

11.代碼演示:

package cn.wwh.www.java.jdbc;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

/**
 *類的作用:用來練習(xí)JDBC編程的,連接的數(shù)據(jù)庫是MySQL
 * 
 * 
 * 
 * 
 *@author 一葉扁舟
 *@version 1.0
 *@創(chuàng)建時間: 2014-8-7 下午08:28:42
 */
public class FirstJDBC {
	/**
	 *建表語句: 
	  drop table if exists person; 
	  create table person( 
	  id int primary key auto_increment,
	  name char(12),
	  password char(12),
	  sex char(2) );
	 insert into person values(1,"wuhui",123456,"男"); 
	 insert into person values(2,"一葉扁舟",123456,"男");
	 */
	private static String driverClass = "com.mysql.jdbc.Driver";
	private static String url = "jdbc:mysql://127.0.0.1:3306/user";
	private static String user = "root";
	private static String password = "wwh";

	public static void main(String[] args) throws Exception {
		//		
		// 1.加載驅(qū)動
		// (1).方式1:
		// DriverManager.registerDriver(new Driver());
		// (2).方式2:利用反射的方式
		Class.forName(driverClass);
		// 使用DriverManager獲取數(shù)據(jù)的連接,
		// 其中返回的Connection就代表java程序和數(shù)據(jù)庫的連接
		/**
		 * @param url
		 *            jdbc:subprotocol:subname 形式的數(shù)據(jù)庫 url
		 * @param user
		 *            數(shù)據(jù)庫用戶,連接是為該用戶建立的
		 * @param password
		 *            登錄數(shù)據(jù)庫的密碼
		 */
		Connection conn = DriverManager.getConnection(url, user, password);

		Statement statement = conn.createStatement();
		String sql = "select * from person;";
		// 執(zhí)行SQL命令,并返回符合條件的記錄集合
		ResultSet result = statement.executeQuery(sql);
		// 采用兩種方式接受查詢的結(jié)果
		while (result.next()) {
			// 獲取第1列的數(shù)據(jù)id
			int id = result.getInt(1);
			// 獲取字段是name的數(shù)據(jù)結(jié)果
			String name = result.getString("name");
			String password = result.getString(3);
			String sex = result.getNString("sex");

			System.out.println("id=" + id + "\tname=" + name + "\tpassword="
					+ password + "\tsex=" + sex);
		}
		// 一次關(guān)閉數(shù)據(jù)庫流
		result.close();
		statement.close();
		conn.close();

	}

}
代碼的測試效果截圖:

\
?

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Applying Semantic Structure with article, section, and aside in HTML Applying Semantic Structure with article, section, and aside in HTML Jul 05, 2025 am 02:03 AM

The rational use of semantic tags in HTML can improve page structure clarity, accessibility and SEO effects. 1. Used for independent content blocks, such as blog posts or comments, it must be self-contained; 2. Used for classification related content, usually including titles, and is suitable for different modules of the page; 3. Used for auxiliary information related to the main content but not core, such as sidebar recommendations or author profiles. In actual development, labels should be combined and other, avoid excessive nesting, keep the structure simple, and verify the rationality of the structure through developer tools.

Selecting Specific Columns | Performance Optimization Selecting Specific Columns | Performance Optimization Jun 27, 2025 pm 05:46 PM

Selectingonlyneededcolumnsimprovesperformancebyreducingresourceusage.1.Fetchingallcolumnsincreasesmemory,network,andprocessingoverhead.2.Unnecessarydataretrievalpreventseffectiveindexuse,raisesdiskI/O,andslowsqueryexecution.3.Tooptimize,identifyrequi

The requested operation requires elevation Windows The requested operation requires elevation Windows Jul 04, 2025 am 02:58 AM

When you encounter the prompt "This operation requires escalation of permissions", it means that you need administrator permissions to continue. Solutions include: 1. Right-click the "Run as Administrator" program or set the shortcut to always run as an administrator; 2. Check whether the current account is an administrator account, if not, switch or request administrator assistance; 3. Use administrator permissions to open a command prompt or PowerShell to execute relevant commands; 4. Bypass the restrictions by obtaining file ownership or modifying the registry when necessary, but such operations need to be cautious and fully understand the risks. Confirm permission identity and try the above methods usually solve the problem.

Redis vs databases: what are the limits? Redis vs databases: what are the limits? Jul 02, 2025 am 12:03 AM

Redisislimitedbymemoryconstraintsanddatapersistence,whiletraditionaldatabasesstrugglewithperformanceinreal-timescenarios.1)Redisexcelsinreal-timedataprocessingandcachingbutmayrequirecomplexshardingforlargedatasets.2)TraditionaldatabaseslikeMySQLorPos

Windows search bar not typing Windows search bar not typing Jul 02, 2025 am 10:55 AM

When the Windows search bar cannot enter text, common solutions are: 1. Restart the Explorer or computer, open the Task Manager to restart the "Windows Explorer" process, or restart the device directly; 2. Switch or uninstall the input method, try to use the English input method or Microsoft's own input method to eliminate third-party input method conflicts; 3. Run the system file check tool, execute the sfc/scannow command in the command prompt to repair the system files; 4. Reset or rebuild the search index, and rebuild it through the "Index Options" in the "Control Panel". Usually, we start with simple steps first, and most problems can be solved step by step.

What is the significance of the Oracle instance, and how does it relate to the database? What is the significance of the Oracle instance, and how does it relate to the database? Jun 28, 2025 am 12:01 AM

AnOracleinstanceistheruntimeenvironmentthatenablesaccesstoanOracledatabase.Itcomprisestwomaincomponents:theSystemGlobalArea(SGA)andbackgroundprocesses.1.TheSGAincludesthedatabasebuffercache,redologbuffer,andsharedpool,whichmanagedataandSQLstatements.

Windows automatic repair loop fix Windows automatic repair loop fix Jul 07, 2025 am 01:31 AM

Use the installation media to enter the recovery environment; 2. Run the bootrec command to repair the boot records; 3. Check for disk errors and repair system files; 4. Disable automatic repair as a temporary means. The Windows automatic repair loop is usually caused by system files corruption, hard disk errors or boot configuration abnormalities. The solution includes troubleshooting by installing the USB flash drive into the recovery environment, using bootrec to repair MBR and BCD, running chkdsk and DISM/sfc to repair disk and system files. If it is invalid, the automatic repair function can be temporarily disabled, but the root cause needs to be checked later to ensure that the hard disk and boot structure are normal.

Performing database schema migrations in MySQL Performing database schema migrations in MySQL Jul 06, 2025 am 02:51 AM

Database schema migration refers to the process of modifying the database structure without changing the data, which mainly includes adding or deleting tables, modifying column types or constraints, creating or deleting indexes, changing default values ??or nullable settings, etc. It is usually driven by application updates, for example, when new features need to store user preferences, new columns are added to the user table. Unlike data migrations that deal with large amounts of data movement, pattern migration focuses on structural changes. To perform mode migrations safely, version control should be used to track structure files, verify them in the test environment before the production environment, split the large migration into small steps, avoid multiple irrelevant changes in a single time, and note that changes to large tables may cause long-term table locking problems. You can use tools such as pt-online-schema-chan.

See all articles