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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
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)

How do you alter a table in MySQL using the ALTER TABLE statement? How do you alter a table in MySQL using the ALTER TABLE statement? Mar 19, 2025 pm 03:51 PM

The article discusses using MySQL's ALTER TABLE statement to modify tables, including adding/dropping columns, renaming tables/columns, and changing column data types.

How do I configure SSL/TLS encryption for MySQL connections? How do I configure SSL/TLS encryption for MySQL connections? Mar 18, 2025 pm 12:01 PM

Article discusses configuring SSL/TLS encryption for MySQL, including certificate generation and verification. Main issue is using self-signed certificates' security implications.[Character count: 159]

How do you handle large datasets in MySQL? How do you handle large datasets in MySQL? Mar 21, 2025 pm 12:15 PM

Article discusses strategies for handling large datasets in MySQL, including partitioning, sharding, indexing, and query optimization.

What are some popular MySQL GUI tools (e.g., MySQL Workbench, phpMyAdmin)? What are some popular MySQL GUI tools (e.g., MySQL Workbench, phpMyAdmin)? Mar 21, 2025 pm 06:28 PM

Article discusses popular MySQL GUI tools like MySQL Workbench and phpMyAdmin, comparing their features and suitability for beginners and advanced users.[159 characters]

How do you drop a table in MySQL using the DROP TABLE statement? How do you drop a table in MySQL using the DROP TABLE statement? Mar 19, 2025 pm 03:52 PM

The article discusses dropping tables in MySQL using the DROP TABLE statement, emphasizing precautions and risks. It highlights that the action is irreversible without backups, detailing recovery methods and potential production environment hazards.

How do you create indexes on JSON columns? How do you create indexes on JSON columns? Mar 21, 2025 pm 12:13 PM

The article discusses creating indexes on JSON columns in various databases like PostgreSQL, MySQL, and MongoDB to enhance query performance. It explains the syntax and benefits of indexing specific JSON paths, and lists supported database systems.

How do you represent relationships using foreign keys? How do you represent relationships using foreign keys? Mar 19, 2025 pm 03:48 PM

Article discusses using foreign keys to represent relationships in databases, focusing on best practices, data integrity, and common pitfalls to avoid.

How do I secure MySQL against common vulnerabilities (SQL injection, brute-force attacks)? How do I secure MySQL against common vulnerabilities (SQL injection, brute-force attacks)? Mar 18, 2025 pm 12:00 PM

Article discusses securing MySQL against SQL injection and brute-force attacks using prepared statements, input validation, and strong password policies.(159 characters)

See all articles