import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
import org.apache.log4j.Logger;
public class JdbcUtil {
public static Logger logger = Logger.getLogger(JdbcUtil.class.getName());
public static Connection
getConnection() {
String jdbc_url =
null;
String jdbc_driver =
null;
String jdbc_name =
null;
String jdbc_password =
null;
try {
Properties prop =
new Properties();
InputStream inStream =
new FileInputStream(
new File(
"config/database.properties"));
prop.load(inStream);
jdbc_url = prop.getProperty(
"jdbc_url");
jdbc_driver = prop.getProperty(
"jdbc_driver");
jdbc_name = prop.getProperty(
"jdbc_name");
jdbc_password = prop.getProperty(
"jdbc_password");
}
catch (FileNotFoundException e1) {
e1.printStackTrace();
}
catch (IOException e1) {
e1.printStackTrace();
}
Connection con =
null;
try {
Class.forName(jdbc_driver);
con = DriverManager.getConnection(jdbc_url +
"?user=" + jdbc_name +
"&password=" + jdbc_password +
"&useUnicode=true&characterEncoding=utf-8");
}
catch (Exception e) {
System.out.println(
"数据库连接失败" + e.getMessage());
}
return con;
}
public static void insert(String sql) {
Connection conn = getConnection();
try {
logger.info(
"jdbc插入数据开始");
Statement statement = (Statement) conn.createStatement();
int count = statement.executeUpdate(sql);
System.out.println(
"更新 " + count +
" 条数据");
statement.close();
conn.close();
logger.info(
"jdbc插入数据结束");
}
catch (SQLException e) {
System.out.println(
"插入数据失败" + e.getMessage());
}
}
public static void update(String sql) {
Connection conn = getConnection();
try {
Statement statement = (Statement) conn.createStatement();
int count = statement.executeUpdate(sql);
System.out.println(
"更新 " + count +
" 条数据");
statement.close();
conn.close();
}
catch (SQLException e) {
System.out.println(
"更新数据失败");
}
}
public static String
query(String sql,String queryContent) {
Connection conn = getConnection();
String queryContentTemp =
"";
try {
Statement statement = (Statement) conn.createStatement();
ResultSet rs = statement.executeQuery(sql);
while (rs.next()) {
queryContentTemp = rs.getString(queryContent);
}
rs.close();
statement.close();
conn.close();
}
catch (SQLException e) {
e.printStackTrace();
}
return queryContentTemp;
}
public static void delete(String sql) {
Connection conn = getConnection();
try {
logger.info(
"jdbc删除数据开始");
Statement statement = (Statement) conn.createStatement();
int count = statement.executeUpdate(sql);
System.out.println(
"agent表中删除了【 " + count +
" 】条数据。");
statement.close();
conn.close();
logger.info(
"jdbc删除数据结束");
}
catch (SQLException e) {
System.out.println(
"删除数据失败");
}
}
}
转载于:https://www.cnblogs.com/bilaisheng/p/10211020.html
相关资源:java高效开发小工具-jdbcutil2