`

JDBC 连接MySql数据库

阅读更多

当然,首先是去mysql的官方网站上,下载mysql的jar包。然后,将mysql相应的JDBC的jar包,

mysql-connector-java-5.1.8-bin.jar导入工程中的WEB-INF\lib文件夹中。

 

1.加载及注册JDBC驱动程序

Class.forName("com.mysql.jdbc.Driver");

Class.forName("com.mysql.jdbc.Driver").newInstance();

 

2.JDBC URL 定义驱动程序与数据源之间的连接

标准语法:

<protocol(主要通讯协议)>:<subprotocol(次要通讯协议,即驱动程序名称)>:<data source identifier(数据源)>

MySQLJDBC URL格式:

jdbc:mysql//[hostname][:port]/[dbname][?param1=value1][&param2=value2]….

 

示例:jdbc:mysql://localhost:3306/sample_db?user=root&password=your_password

 

常见参数:

user                       用户名

password                  密码

autoReconnect                  联机失败,是否重新联机(true/false

maxReconnect              尝试重新联机次数

initialTimeout               尝试重新联机间隔

maxRows                   传回最大行数

useUnicode                 是否使用Unicode字体编码(true/false

characterEncoding          何种编码(GB2312/UTF-8/…

relaxAutocommit            是否自动提交(true/false

capitalizeTypeNames        数据定义的名称以大写表示

3.建立连接对象

String url="jdbc:mysql://localhost:3306/sample_db?user=root&password=your_password";

Connection con = DriverManager.getConnection(url);

 

4.例子:

import java.sql.*;

public class ConnMysql
{
	public static void main(String[] args)
	{
		try
		{
			Class.forName("com.mysql.jdbc.Driver");
			String url="jdbc:mysql://localhost:3306/test?user=root&password=root";

			Connection con = DriverManager.getConnection(url);
			Statement stmt = con.createStatement();			

			String query = "select * from person"; 
			ResultSet rs=stmt.executeQuery(query); 		

			while(rs.next()) 
			{
				System.out.println(rs.getString(2));				
			} 
		}
		catch (ClassNotFoundException e)
		{
			e.printStackTrace();
		}
		catch(SQLException e)
		{
			e.printStackTrace();
		}
		
	}
}

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics