赞
踩
首先必须要下载好相应版本的驱动jar包
下载链接:http://download.csdn.net/detail/acm_th/9190347
方法一:利用Driver接口获取连接
首先在src目录下新建一个jdbc.properties文件
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/hello
user=root
password=123456
SqlConnectDemo.java
package com.xieth.again;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;
public class SqlConnectDemo {
public SqlConnectDemo() throws Exception {
String driverClass = null;
String jdbcUrl = null;
String user = null;
String password = null;
InputStream in = getClass().getClassLoader().getResourceAsStream(
"jdbc.properties"); // 获取流
Properties properties = new Properties();
properties.load(in);
driverClass = properties.getProperty("driver");
jdbcUrl = properties.getProperty("url");
user = properties.getProperty("user");
password = properties.getProperty("password");
Properties info = new Properties();
info.put("user", user);
info.put("password", password);
//通过反射获取Driver对象
Driver driver = (Driver) Class.forName(driverClass).newInstance();
Connection connection = driver.connect(jdbcUrl, info);
System.out.println(connection);
}
public static void main(String[] args) throws Exception {
new SqlConnectDemo();
}
}
运行结果:
连接成功
方法二:利用DriverManager获取连接
public SqlConnectDemo() throws Exception {
String driverClass = null;
String jdbcUrl = null;
String user = null;
String password = null;
InputStream in = getClass().getClassLoader().getResourceAsStream(
"jdbc.properties"); // 获取流
Properties properties = new Properties();
properties.load(in);
driverClass = properties.getProperty("driver");
jdbcUrl = properties.getProperty("url");
user = properties.getProperty("user");
password = properties.getProperty("password");
Connection connection = DriverManager.getConnection(jdbcUrl, user, password);
System.out.println(connection);
}
关键代码就是这一个,替换了 反射操作:
Connection connection = DriverManager.getConnection(jdbcUrl, user, password);
方法三:常用就是这个 简单
public void method2() throws Exception {
String driverClass = "com.mysql.jdbc.Driver";
String jdbcUrl = "jdbc:mysql:///hello";//localhost可以省略
String user = "root";
String password = "123456";
Class.forName(driverClass); // 注册加载驱动
System.out.println(DriverManager.getConnection(jdbcUrl, user, password)); // 获取数据库连接
}
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。