1、加载jdbc驱动
2、提供jdbc连接url
3、创建数据库连接
4、创建statement
5、执行SQL语句
6、对结果进行处理
7、关闭jdbc对象
例子如下:
public class Dbconnection {
private static Connection con = null;
// 驱动程序名
private static String driveName = "com.mysql.jdbc.Driver";
// 数据库用户名
private static String userName = "root";
// 密码
private static String userPasswd = "123456";
// 数据库名字
private static String dbName = "login";
// 连接字符串
private static String url = "jdbc:mysql://localhost/" + dbName + "?user="
+ userName + "&password=" + userPasswd
+ "&useUnicode=true&characterEncoding=gbk";
public static Connection getConnection() {
try {
Class.forName(driveName);
con = DriverManager.getConnection(url);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
return con;
}
public static void close() {
if (con != null) {
try {
con.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}