JDBC连接数据库笔记
时间:2021-07-01 10:21:17
帮助过:2人阅读
package com.java.jdbc;
2
3 import java.sql.DriverManager;
4 import java.sql.SQLException;
5
6 import com.mysql.jdbc.Connection;
7
8 public class JdbcDemo {
9 // MySQL驱动名
10 private static String jdbcName = "com.mysql.jdbc.Driver"
;
11 // MySQL数据库连接地址
12 private static String dbUrl = "jdbc:mysql://localhost:3306/test"
;
13 // MySQL数据库用户名
14 private static String dbUser = "root"
;
15 private static String dbPassword = "12345"
;
16
17 public static void main(String[] args) {
18 try {
19 Class.forName(jdbcName);
20 System.out.println("加载数据库驱动成功"
);
21 }
catch (ClassNotFoundException e) {
22 // TODO Auto-generated catch block
23 e.printStackTrace();
24 System.out.println("加载数据库驱动失败"
);
25 }
26 Connection con =
null;
27 try {
28 con =
(Connection) DriverManager.getConnection(dbUrl, dbUser,
29 dbPassword);
30 System.out.println("数据库连接成功"
);
31 }
catch (SQLException e) {
32 // TODO Auto-generated catch block
33 e.printStackTrace();
34 System.out.println("数据库连接失败"
);
35 }
36 if (con !=
null) {
37 try {
38 con.close();
39 System.out.println("数据库关闭成功"
);
40 }
catch (SQLException e) {
41 // TODO Auto-generated catch block
42 e.printStackTrace();
43 }
44 }
45 }
46
47 }
JDBC连接数据库笔记
标签: