利用jdbc方式连接数据库。
1.添加mysql驱动jar包
我用的是这个驱动包mysql-connector-java-5.1.26-bin.jar
添加方式:
2.加载MySql驱动类
private void LoadDriver() {
try {
String forName = "com.mysql.jdbc.Driver";
// 加载MySql的驱动类
Class.forName(forName);
System.out.println("MySql驱动加载成功");
} catch (ClassNotFoundException e) {
System.out.println("找不到驱动程序类 ,加载驱动失败!");
// e.printStackTrace();
}
}
3.连接数据库
public void OpenLik() {
try {
String url = "jdbc\:mysql\://localhost\:3306/test1";
String username = "root";
String password = "root";
System.out.println(url + username + password);
con = DriverManager.getConnection(url, username, password);
System.out.println("数据库连接成功!");
} catch (SQLException se) {
System.out.println("数据库连接失败!");
// se.printStackTrace();
}
}
4.创建数据库执行命令,并传入sql 操作语句
public Statement GetSqlStringCommand(String query) {
// TODO Auto-generated method stub
PreparedStatement pstmt = null;
try {
pstmt = con.prepareStatement(query);
System.out.println("获取命令成功");
} catch (Exception ex) {
System.out.println("获取命令失败");
// ex.printStackTrace();
}
return pstmt;
}
5.根据数据库命令,操作sql命令语句
public ResultSet ExecuteDataSet(Statement cmd) {
// TODO Auto-generated method stub
ResultSet RS = null;
PreparedStatement cmd_ = (PreparedStatement) cmd;
try {
RS = cmd_.executeQuery();
System.out.println("获取ResultSet成功");
} catch (Exception ex) {
System.out.println("获取ResultSet失败");
// ex.printStackTrace();
}
return RS;
}
这样就可以进行数据库的连接了!!!