1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
|
package
lin.test;
import
java.sql.*;
public
class
Test
{
public
static
void
main(String[] args)
{
//驱动程序名
String driveName =
"com.mysql.jdbc.Driver"
;
//URL指向要访问的数据库名test
String databaseURL =
"jdbc:mysql://localhost:3306/test"
;
//MySQL配置时的用户名
String user =
"root"
;
//MySQL配置时的密码
String password =
"root"
;
// 此处写自己的密码
try
{
//加载驱动
Class.forName(driveName);
System.out.println(
"成功加载数据库驱动程序"
);
}
catch
(java.lang.ClassNotFoundException e)
{
System.out.println(
"加载数据库驱动程序失败"
);
System.out.println(
"加载数据库驱动程序失败"
);
System.out.println(e.getMessage());
return
;
}
try
{
/连续MySQL数据库
Connection con = DriverManager.getConnection(databaseURL, user,password);
System.out.println(
"连接数据库成功"
);
//关闭连接
con.close();
}
catch
(SQLException e)
{
System.out.println(
"连接数据库失败"
);
System.out.println(
"SQLException:"
+ e.getMessage());
return
;
}
}
}
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
|
/ * When a Driver
class
is loaded, it should create an instance of itself and register it with the DriverManager. This means that a user can load and register a driver by doing Class.forName(
"foo.bah.Driver"
)
*/
package
com.mysql.jdbc;
import
java.sql.SQLException;
public
class
Driver
extends
NonRegisteringDriver
implements
java.sql.Driver {
// ~ Static fields/initializers
// ---------------------------------------------
//
// Register ourselves with the DriverManager
//
static
{
try
{ java.sql.DriverManager.registerDriver(
new
Driver());
}
catch
(SQLException E) {
throw
new
RuntimeException(
"Can't register driver!"
);
}
}
// ~ Constructors
// -----------------------------------------------------------
/**
* Construct a new driver and register it with DriverManager
*
* @throws SQLException
* if a database error occurs.
*/
public
Driver()
throws
SQLException {
// Required for Class.forName().newInstance()
}
}
|