首页 > 数据库技术 > 详细

jdbc初学者连接

时间:2015-11-24 20:18:56      阅读:303      评论:0      收藏:0      [点我收藏+]

创建properties文件

jdbc.properties

文件内容:

driver=com.mysql.jdbc.Driver//驱动目录
url=jdbc:mysql://localhost:3306/dangdang//
username=root
password=root  /密码

建立类 LoadProperties 装载jdbc.properties

package com.xinhua.utils;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

public class LoadProperties {

public static Properties properties = new Properties();

static{

InputStream in = LoadProperties.class.getClassLoader().getResourceAsStream("jdbc.properties");

try {
properties.load(in);

} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

public static String getProperties(String key){
return properties.getProperty(key);
}
}

 

建立常量 Constant接受四个参数

package com.xinhua.constant;

import com.xinhua.utils.LoadProperties;

public class Constant {

public static String USERNAME = LoadProperties.getProperties("username");
public static String URL = LoadProperties.getProperties("url");
public static String DRIVER = LoadProperties.getProperties("driver");
public static String PASSWORD = LoadProperties.getProperties("password");
}

 

建立工具类DBUtils 

package com.xinhua.utils;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import com.xinhua.constant.Constant;

public class DBUtils {

public static Connection getConnection() {

try {
Class.forName(Constant.DRIVER);
return DriverManager.getConnection(Constant.URL, Constant.USERNAME,
Constant.PASSWORD);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}

return null;
}

public static void closeConnection(Connection connection,
PreparedStatement ps) {

if (ps != null) {
try {
ps.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

public static void closeConnection(Connection connection,
PreparedStatement ps, ResultSet rs) {
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (ps != null) {
try {
ps.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}

 

工具类一般使用static方法

该方法还未加入连接池

后续学习过程中在加入

jdbc初学者连接

原文:http://www.cnblogs.com/pi-qingwen/p/4992652.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!