Home > Database > Mysql Tutorial > body text

Java连接各种数据库代码和驱动

WBOY
Release: 2016-06-07 15:28:55
Original
1621 people have browsed it

1、这里介绍java代码连接常用数据库的方式,数据库包括MySQL、Sybase、Oracle、SqlServer,连接数据库都是需要在工程里添加jar包加载驱动的,这几个jar包我整理好放在csdn资源中了,下载地址:http://download.csdn.net/detail/wangduanqing5945/7004093 2、

1、这里介绍java代码连接常用数据库的方式,数据库包括MySQL、Sybase、Oracle、SqlServer,连接数据库都是需要在工程里添加jar包加载驱动的,这几个jar包我整理好放在csdn资源中了,下载地址:http://download.csdn.net/detail/wangduanqing5945/7004093

2、MySQL连接

Connection connection = null;
		try {
			Class.forName("com.mysql.jdbc.Driver");
			connection = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/boxmanager", "username", "password");
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		}
Copy after login

这里为没有用过的朋友解释一下,com.mysql.jdbc.Driver这是MySQL中Driver类的包名加类名,固定写法。下面getConnection方法中有三个参数,第一个数据库地址,对应到某个数据库,第二个参数是数据库用户名,第三个为数据库密码。

3、Sybase连接

try {
			String driver = "com.sybase.jdbc3.jdbc.SybDriver";
			Class.forName(driver).newInstance();
			String url = "jdbc:sybase:Tds:192.168.100.252:4500/myDB";//
			// myDB为你的数据库名
			Properties sysProps = System.getProperties();
			sysProps.put("user", username); // 设置数据库访问用户名
			sysProps.put("password", password); // 密码
			connection = DriverManager.getConnection(url, sysProps);
		} catch (Exception e) {
			e.printStackTrace();
		}
Copy after login

想必看懂上面解释的,这里就不用解释了吧,思想都是一致的。

4、Oracle连接

// 得到连接
		Connection ct = null;
		try {
			// 加载驱动
			Class.forName("oracle.jdbc.driver.OracleDriver");
			ct = DriverManager.getConnection(
					"jdbc:oracle:thin:@127.0.0.1:1521:simlink", "your username", "your pwd");
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		}
Copy after login

5、SqlServer连接

String driverName = "com.microsoft.jdbc.sqlserver.SQLServerDriver";
		String dbURL = "jdbc:microsoft:sqlserver://localhost:1433;databasename=li"; // 1433是数据库的端口,"li"是你的数据库名称
		String userName = "sa"; // sa是数据库的超级用户,最好不要换别的名字,权限问题
		String userPwd = "123456"; // sa的密码

		Connection dbConn = null;
		try {
			Class.forName(driverName).newInstance();
			dbConn = DriverManager.getConnection(dbURL, userName, userPwd);
			System.out.println("连接成功!");
		} catch (Exception e) {
			e.printStackTrace();
		}
Copy after login



Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template