- 声明:以下方式是循序渐进的,都是在前一种方式的完善的过程,对前一种方式的完善。前四种了解过程,重点掌握最后一种。
- 方式一
- 1.具体步骤
- 2.代码实现
- 方式二
- 1.改进
- 2.代码实现
- 方式三
- 1.改进
- 2.代码实现
- 方式四
- 1.改进
- 2.代码实现
- 方式五
- 1.最终版(推荐使用)
- 2.代码实现
- 常见异常及处理方式
1.获取连接,使用Driver接口
2.将用户名与密码封装
3.调用connect方法来返回一个Connection对象,这是一个连接
public class Test01 {
@Test
public void textConnection() throws SQLException {
//1.获取连接,使用Driver接口
Driver driver=new com.mysql.jdbc.Driver();//需要用一个Mysql具体的driver的实现类
String url="jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8";//定位要连接哪一个数据库,?后面的内容,是编码转换异常时加的
//2.将用户名与密码封装
Properties info=new Properties();
info.setProperty("user","root");
info.setProperty("password","123456");
//3.调用connect方法来返回一个Connection对象,这是一个连接
Connection connect = driver.connect(url, info);
System.out.println(connect);//检查是否连接成功
}
}
方式二
1.改进
1.代码当中尽量不要出现过多的第三方API,运用反射
2.代码实现public void Test02() throws Exception{
//1.获取Driver的实现类对象(用反射):动态的获取
Class clazz= Class.forName("com.mysql.jdbc.Driver");
Driver driver = (Driver) clazz.newInstance();
String url="jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8";
Properties info=new Properties();
info.setProperty("user","root");
info.setProperty("password","123456");
Connection connection= driver.connect(url,info);
System.out.println(connection);
}
}
方式三
1.改进
使用DriverManager来替换Driver
2.代码实现public class Test03 {
@Test
public void three() throws Exception {
//1.获取基本信息
Class clazz= Class.forName("com.mysql.jdbc.Driver");
Driver driver = (Driver) clazz.newInstance();
String url="jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8";
String user="root";
String password="123456";
//2.注册驱动
DriverManager.registerDriver(driver);
//3获取连接
Connection cc = DriverManager.getConnection(url, user, password);
System.out.println(cc);
}
}
方式四
1.改进
2.代码实现
public class Text04 {
@Test
public void text() throws Exception {
//1.获取基本信息
String url="jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8";
String user="root";
String password="123456";
//2.获取基本类的实现对象 注册驱动
Class.forName("com.mysql.jdbc.Driver");//连接mysql数据库时,这行也可以注释掉,Oracle不行
//3.获取连接
Connection cc = DriverManager.getConnection(url, user, password);
System.out.println(cc);
}
}
方式五
1.最终版(推荐使用)
将信息封装到配置文件中,通过读取配置文件的方式
- 这种方案的好处:实现了数据与代码的分离
- 如果要修改文件,避免了文件的重新打包
public class Text05 {
@Test
public void Text5() throws Exception{
//1.读取配置文件中的基本信息
InputStream is = Text05.class.getClassLoader().getResourceAsStream("jdbc.properties");
Properties properties = new Properties();
properties.load(is);
String user = properties.getProperty("user");
String password = properties.getProperty("password");
String url = properties.getProperty("url");
String driverClass = properties.getProperty("driverClass");
//2.加载驱动
Class.forName(driverClass);
//3.获取连接
Connection connection = DriverManager.getConnection(url, user, password);
System.out.println(connection);
}
}
常见异常及处理方式
1.
解决:
数据库未连接
2.
编码集的问题
解决:
连接数据库只是jdbc学习过程中的一个基础。后面我会出超详细的教程。增删改查。



