jdbc动态建表、插入记录、查询等功能(mysql)

导读:本篇文章讲解 jdbc动态建表、插入记录、查询等功能(mysql),希望对大家有帮助,欢迎收藏,转发!站点地址:www.bmabk.com

最近遇到一个项目,需要使用jdbc判断数据库中table是否存在,并实现动态的创建,添加记录和相关的查询,自己经过学习,实现了这个功能,并可以导入为jar包,动态的使用。

一:实现数据库的连接(通过配置文件实现)

package com.delta.smarthome.utils;

import java.io.FileInputStream;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.Driver;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Properties;

public class JDBCUtil {
public static Connection getConnection() throws Exception{
String driverClass=null;
String jdbcUrl=null;
String user=null;
String pwd=null;
InputStream in = new FileInputStream(“src/config.properties”);
Properties properties=new Properties();
properties.load(in);

   driverClass=properties.getProperty("driver");

   jdbcUrl=properties.getProperty("url");
   user=properties.getProperty("user");

   pwd=properties.getProperty("pwd");
   Driver driver=(Driver) Class.forName(driverClass).newInstance();
   Properties info=new Properties();
   info.put("user",user);
   info.put("password",pwd);
   Connection connection=driver.connect(jdbcUrl, info);
   return connection;

}
public static void close(Connection conn,PreparedStatement ps, Statement st, ResultSet rs) {

if (rs != null) {
try {
rs.close();
} catch (Exception e) {
e.printStackTrace();
}
rs = null;
}
if (ps != null) {
try {
ps.close();
} catch (Exception e) {
e.printStackTrace();
}
}
if (st != null) {
try {
st.close();
} catch (Exception e) {
e.printStackTrace();
}
}

if (conn != null) {
try {
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}

@SuppressWarnings(“static-access”)
public static void main(String[] args) {
JDBCUtil jdbcUtil=new JDBCUtil();
try {
System.out.println(jdbcUtil.getConnection());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
二:数据库动态操作类(在该类中实现了数据库中表是否存在的判断,动态建表,插入数据,动态查询,分页查询等,这些功能只需要你提供表名,表的相关字段属性,就可以自动实现)

package com.delta.smarthome.sql;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import com.delta.smarthome.utils.JDBCUtil;
import com.mysql.jdbc.Statement;

public class DatabaseOperations {
public static Connection conn = null;
public static PreparedStatement ps = null;

/**
* 判断表是否存在
*
* @param tabName
* @return
* @throws SQLException
*/
public static boolean exitTable(String tabName) {
ResultSet resultSet = null;
Statement stmt = null;
boolean flag = false;
try {
conn = JDBCUtil.getConnection();
conn.setAutoCommit(false);
stmt = (Statement) conn.createStatement();
String sql = “show tables like ‘” + tabName + “’;”;
resultSet = stmt.executeQuery(sql);
if (resultSet.next()) {
flag = true;
}
conn.commit();
} catch (SQLException e) {
System.out.println(“查询失败:” + e.getMessage());
try {
conn.rollback();
} catch (SQLException e1) {
System.out.println(“回滚失败:” + e1.getMessage());
}

} catch (Exception e2) {
System.out.println(“查询失败” + e2.getMessage());
} finally {
// 关闭数据库连接
JDBCUtil.close(conn, ps, stmt, resultSet);
}
return flag;
}

/**
* 创建表
*
* @param tabName
* 表名称
* @param tab_fields
* 表字段
* @throws Exception
*/
public static void createTable(String tabName, String[] tab_fields) {
try {
conn = JDBCUtil.getConnection(); // 首先要获取连接,即连接到数据库
conn.setAutoCommit(false);
String sql = “create table ” + tabName
+ “(id int auto_increment primary key not null”;
if (tab_fields != null && tab_fields.length > 0) {
sql += “,”;
int length = tab_fields.length;
for (int i = 0; i < length; i++) {
// 添加字段
sql += tab_fields[i].trim() + ” varchar(50)”;
// 防止最后一个,
if (i < length – 1) {
sql += “,”;
}
}
}
// 拼凑完 建表语句 设置默认字符集
sql += “,saveTime varchar(64) DEFAULT NULL)DEFAULT CHARSET=utf8;”;
System.out.println(“添加数据的sql:” + sql);
ps = conn.prepareStatement(sql);
ps.executeUpdate(sql);
conn.commit();
} catch (SQLException e) {
System.out.println(“建表失败” + e.getMessage());
try {
conn.rollback();
} catch (SQLException e1) {
System.out.println(“回滚失败:” + e1.getMessage());
}

} catch (Exception e2) {
System.out.println(“建表失败” + e2.getMessage());
} finally {
// 关闭数据库连接
JDBCUtil.close(conn, ps, null, null);

}
}

/**
* 添加数据
*
* @param tabName
* 表名
* @param fields
* 参数字段
* @param data
* 参数字段数据
* @throws Exception
*/
public static void insert(String tabName, String[] fields, String[] data) {

try {
conn = JDBCUtil.getConnection(); // 首先要获取连接,即连接到数据库
conn.setAutoCommit(false);
String sql = “insert into ” + tabName + “(“;
int length = fields.length;
for (int i = 0; i < length; i++) {
sql += fields[i];
// 防止最后一个,
if (i < length – 1) {
sql += “,”;
}
}
sql += “,saveTime) values(“;
for (int i = 0; i < length; i++) {
sql += “?”;
// 防止最后一个,
if (i < length – 1) {
sql += “,”;
}
}
sql += “,now());”;
System.out.println(“添加数据的sql:” + sql);
// 预处理SQL 防止注入
excutePs(sql, length, data);
// 执行
ps.executeUpdate();
conn.commit();
} catch (SQLException e) {
System.out.println(“添加数据失败” + e.getMessage());
try {
conn.rollback();
} catch (SQLException e1) {
System.out.println(“回滚失败:” + e1.getMessage());
}
} catch (Exception e2) {
System.out.println(“添加数据失败” + e2.getMessage());
} finally {
JDBCUtil.close(conn, ps, null, null);

}
}

/**
* 查询表 【查询结果的顺序要和数据库字段的顺序一致】
*
* @param tabName
* 表名
* @param fields
* 参数字段
* @param data
* 参数字段数据
* @param tab_fields
* 获得的数据库的字段
*/
public static List

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/15916.html

(0)
小半的头像小半

相关推荐

极客之音——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!