Home Database Mysql Tutorial JDK+JDBC+MySQL实例及注意事项_MySQL

JDK+JDBC+MySQL实例及注意事项_MySQL

May 31, 2016 am 08:50 AM

by qx.zhong

Hangzhou 29 Jun 2014

开发环境

OS:  Win8.1 x64

JDK: 1.8 SE

DB:  MySQL 5.5 

Lib:  mysql-connector-java.jar

1. MySQL数据库数据类型与JDK之间的特殊对应关系

下表只列举几个特殊的值类型对照,其余的又需要可以参考MySQL官网的值类型说明(http://dev.mysql.com/doc/refman/5.1/zh/index.html)以及JDK的相关资料。

MySQL JDK
tinyint(1) boolean
int unsigined  long
datetime java.sql.Timestamp
varchar String

在MySQL中,TINYINT(1)是BOOL, BOOLEAN的同义词带符号的范围是-128到127。无符号的范围是0到255。BOOLEAN非zero为真,zero为假。

INT UNSIGINED值的范围超出了JDK的int类型(JDK中的整形类型都是带符号的)的最大取值范围,所以需要用long装载。

2. 采用JDK的反射机制将JDBC ResultSet的自动加载到Bean类

首先要确保MySQL中的列名和JavaBean类的属性名是一一对应的,然后就可以使用反射机制调用setter对Bean进行赋值,关键代码:

/**	 *Using reflection to storage the result from database into Bean class.	 *	 */	public static List<object> resultSetToList(ResultSet rs, Class> cls) {		Method[] methods = cls.getDeclaredMethods();	int methodLength = methods.length;		int index;	Map<string integer> map = new HashMap<string integer>();	// record all methods name in a HashMap, for quickly locate.	for (index = 0; index  list = new ArrayList<object>(); 		try {		meta = rs.getMetaData();		int colCount = meta.getColumnCount();			while (rs.next()) {			obj = cls.newInstance(); 						for (int i = 1; i <p></p>
<p><strong>3. 其他说明</strong></p>
<p>数据库的连接于释放是JDBC中最耗费时间及系统开销的,因此推荐采用数据库连接池处理。一个池设置最小连接数和最大连接数。</p>
<p>最小连接数是连接池启动时默认的初始化建立的连接,建多了会影响代码的启动时间,建立少了会出现不够用的现象(虽然实际运行中,连接池检测到需求数量大于最小连接数时,会自动新增连接)。</p>
<p>故连接池的最小连接数是需要根据项目实际情况斟酌的。</p>
<p><strong>4. 示例项目</strong></p>
<p>4.1 数据库表设计</p>
<p>1)设计一个cake表,详情如下:</p>
<pre class="brush:php;toolbar:false">mysql> describe cake;+--------------+---------------------+------+-----+---------+-------+| Field| Type| Null | Key | Default | Extra |+--------------+---------------------+------+-----+---------+-------+| name | varchar(20) | NO | PRI | NULL| || serialNumber | int(10) unsigned| YES| | NULL| || buildDate| datetime| YES| | NULL| || isSweet| tinyint(1) unsigned | YES| | NULL| |+--------------+---------------------+------+-----+---------+-------+
Copy after login

2)初始化的数据:

mysql> select * from cake;+--------+--------------+---------------------+---------+| name | serialNumber | buildDate | isSweet |+--------+--------------+---------------------+---------+| Danisa |2021344 | 2013-11-19 10:20:00 | 1 || Orion|2004720 | 2014-06-29 22:00:00 | 0 |+--------+--------------+---------------------+---------+
Copy after login

4.2 Bean类设计

1)Cake类的属性:

private String name; private long serialNumber; private Timestamp buildDate; private boolean isSweet;
Copy after login

2)Bean中特殊值类型变量的Setter的设计细节:

 JDK整形类型的setter参数需用java.lang中的类,如long对应java.lang.Long, int对应java.lang.Integer。

 这样的动机是,可以使Bean的属性符合2中叙述的resultSetToList的形参Class> cls。

 本例中,ResultSet取出的MySql的int unsigned,会自动在内存中转化为Long类型,故setter需要使用Long;

public void setSerialNumber(Long /*long*/ serialNumber) { //Type was java.lang.Long but not 'long'.this. serialNumber = serialNumber; }
Copy after login

 从MySql取出的tinyint(1)存为Boolean,故Bean类的setter形参是Boolean类型。

 此外,属性isSweet在eclipse中自动生成的setter名为setSweet,在反射赋值时,就会出现找不到方法的异常,因为反射赋值搜索的方法是'setissweet',所以要把自动生成的setter改名。

public void /*setSweet*/setIsSweet( /*boolean*/Boolean isSweet) { // Type was java.lang.Boolean but not booleanthis. isSweet = isSweet; }
Copy after login
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

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.

Undress AI Tool

Undress AI Tool

Undress images for free

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 Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

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)

Hot Topics

Java Tutorial
1665
14
PHP Tutorial
1269
29
C# Tutorial
1249
24
MySQL's Role: Databases in Web Applications MySQL's Role: Databases in Web Applications Apr 17, 2025 am 12:23 AM

The main role of MySQL in web applications is to store and manage data. 1.MySQL efficiently processes user information, product catalogs, transaction records and other data. 2. Through SQL query, developers can extract information from the database to generate dynamic content. 3.MySQL works based on the client-server model to ensure acceptable query speed.

Explain the role of InnoDB redo logs and undo logs. Explain the role of InnoDB redo logs and undo logs. Apr 15, 2025 am 12:16 AM

InnoDB uses redologs and undologs to ensure data consistency and reliability. 1.redologs record data page modification to ensure crash recovery and transaction persistence. 2.undologs records the original data value and supports transaction rollback and MVCC.

MySQL: An Introduction to the World's Most Popular Database MySQL: An Introduction to the World's Most Popular Database Apr 12, 2025 am 12:18 AM

MySQL is an open source relational database management system, mainly used to store and retrieve data quickly and reliably. Its working principle includes client requests, query resolution, execution of queries and return results. Examples of usage include creating tables, inserting and querying data, and advanced features such as JOIN operations. Common errors involve SQL syntax, data types, and permissions, and optimization suggestions include the use of indexes, optimized queries, and partitioning of tables.

MySQL's Place: Databases and Programming MySQL's Place: Databases and Programming Apr 13, 2025 am 12:18 AM

MySQL's position in databases and programming is very important. It is an open source relational database management system that is widely used in various application scenarios. 1) MySQL provides efficient data storage, organization and retrieval functions, supporting Web, mobile and enterprise-level systems. 2) It uses a client-server architecture, supports multiple storage engines and index optimization. 3) Basic usages include creating tables and inserting data, and advanced usages involve multi-table JOINs and complex queries. 4) Frequently asked questions such as SQL syntax errors and performance issues can be debugged through the EXPLAIN command and slow query log. 5) Performance optimization methods include rational use of indexes, optimized query and use of caches. Best practices include using transactions and PreparedStatemen

Why Use MySQL? Benefits and Advantages Why Use MySQL? Benefits and Advantages Apr 12, 2025 am 12:17 AM

MySQL is chosen for its performance, reliability, ease of use, and community support. 1.MySQL provides efficient data storage and retrieval functions, supporting multiple data types and advanced query operations. 2. Adopt client-server architecture and multiple storage engines to support transaction and query optimization. 3. Easy to use, supports a variety of operating systems and programming languages. 4. Have strong community support and provide rich resources and solutions.

MySQL vs. Other Programming Languages: A Comparison MySQL vs. Other Programming Languages: A Comparison Apr 19, 2025 am 12:22 AM

Compared with other programming languages, MySQL is mainly used to store and manage data, while other languages ​​such as Python, Java, and C are used for logical processing and application development. MySQL is known for its high performance, scalability and cross-platform support, suitable for data management needs, while other languages ​​have advantages in their respective fields such as data analytics, enterprise applications, and system programming.

MySQL: From Small Businesses to Large Enterprises MySQL: From Small Businesses to Large Enterprises Apr 13, 2025 am 12:17 AM

MySQL is suitable for small and large enterprises. 1) Small businesses can use MySQL for basic data management, such as storing customer information. 2) Large enterprises can use MySQL to process massive data and complex business logic to optimize query performance and transaction processing.

How does MySQL index cardinality affect query performance? How does MySQL index cardinality affect query performance? Apr 14, 2025 am 12:18 AM

MySQL index cardinality has a significant impact on query performance: 1. High cardinality index can more effectively narrow the data range and improve query efficiency; 2. Low cardinality index may lead to full table scanning and reduce query performance; 3. In joint index, high cardinality sequences should be placed in front to optimize query.

See all articles