mysql的util_JDBC连接mysql工具类Util供大家参考
> list = new ArrayList>();
//靜態(tài)代碼塊,在程序編譯的時(shí)候執(zhí)行
static {
//創(chuàng)建Properties對(duì)象
Properties properties = new Properties();
//獲取文件輸入流
InputStream is = JDBCUtil_cj.class.getClassLoader().getResourceAsStream("jdbc.properties");
try {
//加載輸入流
properties.load(is);
is.close();
//加載mysql驅(qū)動(dòng)
Class.forName(properties.getProperty("driver"));
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
//關(guān)閉資源
public static void closeRes(Connection conn,PreparedStatement ps,ResultSet rs) {
try {
if(rs != null){
rs.close();
}
if(ps != null){
ps.close();
}
if(conn != null){
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
//獲取連接
public static Connection getConnection(){
Connection conn = null;
Properties properties = new Properties();
InputStream is = JDBCUtil_cj.class.getClassLoader().getResourceAsStream("jdbc.properties");
try {
properties.load(is);
is.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
conn = DriverManager.getConnection(
properties.getProperty("url"),
properties.getProperty("username"),
properties.getProperty("password"));
} catch (SQLException e) {
e.printStackTrace();
}
return conn;
}
public static void main(String[] args) {
Connection connection = getConnection();
String sql = "select * from dept where deptno = ?";
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
try {
preparedStatement = connection.prepareStatement(sql);
preparedStatement.setInt(1,10);
resultSet = preparedStatement.executeQuery();
ResultSetMetaData md = resultSet.getMetaData(); //獲得結(jié)果集結(jié)構(gòu)信息,元數(shù)據(jù)
int columnCount = md.getColumnCount(); //獲得列數(shù)
while (resultSet.next()) {
MaprowData = new HashMap();
for (int i = 1; i <= columnCount; i++) {
rowData.put(md.getColumnName(i), resultSet.getObject(i));
}
JDBCUtil_cj cj = new JDBCUtil_cj();
cj.list.add(rowData);
for (Map.Entryentry : rowData.entrySet()) {
System.out.println(entry.getKey()+"==="+entry.getValue());
}
System.out.println(rowData);
System.out.println(cj.list);
}
} catch (SQLException e) {
e.printStackTrace();
}
JDBCUtil_cj.closeRes(connection,preparedStatement,resultSet);
}
}
總結(jié)
以上是生活随笔為你收集整理的mysql的util_JDBC连接mysql工具类Util供大家参考的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 杨梅有虫到底能不能吃?专家科普:果蝇幼虫
- 下一篇: 摩托罗拉全球首款2亿像素骁龙8+旗舰来了