java使用JDBC动态创建数据表及SQL预处理的方法

2025-05-29 0 32

本文实例讲述了java使用JDBC动态创建数据表及SQL预处理的方法。分享给大家供大家参考,具体如下:

这两天由于公司的需求,客户需要自定义数据表的字段,导致每张表的字段都不是固定的而且很难有一个通用的模板去维护,所以就使用JDBC动态去创建数据表,然后通过表的字段动态添加数据,数据的来源主要是用户提供的Excel直接导入到数据库中。

如果考虑到字段的类型,可以通过反射的机制去获取,现在主要用户需求就是将数据导入到数据库提供查询功能,不能修改,所以就直接都使用String类型来处理数据更加便捷。

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

104

105

106

107

108

109

110

111

112

113

114

115

116

117

118

119

120

121

122

123

124

125

126

127

128

129

130

131

132

133

134

135

136

137

138

139

140

141

142

143

144

145

146

147

148

149

150

151

152

153

154

155

156

157

158

159

160

161

162

163

164

165

166

167

168

169

170

171

172

173

174

175

176

177

178

179

180

181

182

183

184

185

186

187

188

189

190

191

192

193

194

195

196

197

198

199

200

201

202

203

204

205

206

207

208

209

210

211

212

213

214

215

216

217

218

219

220

221

222

223

224

225

226

227

228

229

230

231

232

233

234

235

236

237

238

239

240

241

242

243

244

245

246

247

248

249

250

251

252

253

254

255

256

257

258

259

260

261

262

263

264

265

266

267

268

269

270

271

272

273

274

275

276

277

278

279

280

281

282

283

284

285

286

287

288

289

290

291

292

293

294

295

296

297

298

299

300

301

302

303

304

305

306

307

308

309

310

311

312

313

314

315
import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.PreparedStatement;

import java.sql.ResultSet;

import java.sql.SQLException;

import java.util.ArrayList;

import java.util.List;

import java.util.PropertyResourceBundle;

import java.util.ResourceBundle;

public class DataBaseSql {

//配置文件 读取jdbc的配置文件

private static ResourceBundle bundle = PropertyResourceBundle.getBundle("db");

private static Connection conn;

private static PreparedStatement ps;

/**

* 创建表

* @param tabName 表名称

* @param tab_fields 表字段

*/

public static void createTable(String tabName,String[] tab_fields) {

conn = getConnection(); // 首先要获取连接,即连接到数据库

try {

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+=")DEFAULT CHARSET=utf8;";

System.out.println("建表语句是:"+sql);

ps = conn.prepareStatement(sql);

ps.executeUpdate(sql);

ps.close();

conn.close(); //关闭数据库连接

} catch (SQLException e) {

System.out.println("建表失败" + e.getMessage());

}

}

/**

* 添加数据

* @param tabName 表名

* @param fields 参数字段

* @param data 参数字段数据

*/

public static void insert(String tabName,String[] fields,String[] data) {

conn = getConnection(); // 首先要获取连接,即连接到数据库

try {

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+=") values(";

for(int i=0;i<length;i++){

sql+="?";

//防止最后一个,

if(i<length-1){

sql+=",";

}

}

sql+=");";

System.out.println("添加数据的sql:"+sql);

//预处理SQL 防止注入

excutePs(sql,length,data);

//执行

ps.executeUpdate();

//关闭流

ps.close();

conn.close(); //关闭数据库连接

} catch (SQLException e) {

System.out.println("添加数据失败" + e.getMessage());

}

}

/**

* 查询表 【查询结果的顺序要和数据库字段的顺序一致】

* @param tabName 表名

* @param fields 参数字段

* @param data 参数字段数据

* @param tab_fields 数据库的字段

*/

public static String[] query(String tabName,String[] fields,String[] data,String[] tab_fields){

conn = getConnection(); // 首先要获取连接,即连接到数据库

String[] result = null;

try {

String sql = "select * from "+tabName+" where ";

int length = fields.length;

for(int i=0;i<length;i++){

sql+=fields[i]+" = ? ";

//防止最后一个,

if(i<length-1){

sql+=" and ";

}

}

sql+=";";

System.out.println("查询sql:"+sql);

//预处理SQL 防止注入

excutePs(sql,length,data);

//查询结果集

ResultSet rs = ps.executeQuery();

//存放结果集

result = new String[tab_fields.length];

while(rs.next()){

for (int i = 0; i < tab_fields.length; i++) {

result[i] = rs.getString(tab_fields[i]);

}

}

//关闭流

rs.close();

ps.close();

conn.close(); //关闭数据库连接

} catch (SQLException e) {

System.out.println("查询失败" + e.getMessage());

}

return result;

}

/**

* 获取某张表总数

* @param tabName

* @return

*/

public static Integer getCount(String tabName){

int count = 0;

conn = getConnection(); // 首先要获取连接,即连接到数据库

try {

String sql = "select count(*) from "+tabName+" ;";

ps = conn.prepareStatement(sql);

ResultSet rs = ps.executeQuery();

while(rs.next()){

count = rs.getInt(1);

}

rs.close();

ps.close();

conn.close(); //关闭数据库连接

} catch (SQLException e) {

System.out.println("获取总数失败" + e.getMessage());

}

return count;

}

/**

* 后台分页显示

* @param tabName

* @param pageNo

* @param pageSize

* @param tab_fields

* @return

*/

public static List<String[]> queryForPage(String tabName,int pageNo,int pageSize ,String[] tab_fields){

conn = getConnection(); // 首先要获取连接,即连接到数据库

List<String[]> list = new ArrayList<String[]>();

try {

String sql = "select * from "+tabName+" LIMIT ?,? ; ";

System.out.println("查询sql:"+sql);

//预处理SQL 防止注入

ps = conn.prepareStatement(sql);

//注入参数

ps.setInt(1,pageNo);

ps.setInt(2,pageSize);

//查询结果集

ResultSet rs = ps.executeQuery();

//存放结果集

while(rs.next()){

String[] result = new String[tab_fields.length];

for (int i = 0; i < tab_fields.length; i++) {

result[i] = rs.getString(tab_fields[i]);

}

list.add(result);

}

//关闭流

rs.close();

ps.close();

conn.close(); //关闭数据库连接

} catch (SQLException e) {

System.out.println("查询失败" + e.getMessage());

}

return list;

}

/**

* 清空表数据

* @param tabName 表名称

*/

public static void delete(String tabName){

conn = getConnection(); // 首先要获取连接,即连接到数据库

try {

String sql = "delete from "+tabName+";";

System.out.println("删除数据的sql:"+sql);

//预处理SQL 防止注入

ps = conn.prepareStatement(sql);

//执行

ps.executeUpdate();

//关闭流

ps.close();

conn.close(); //关闭数据库连接

} catch (SQLException e) {

System.out.println("删除数据失败" + e.getMessage());

}

}

/**

* 用于注入参数

* @param ps

* @param data

* @throws SQLException

*/

private static void excutePs(String sql,int length,String[] data) throws SQLException{

//预处理SQL 防止注入

ps = conn.prepareStatement(sql);

//注入参数

for(int i=0;i<length;i++){

ps.setString(i+1,data[i]);

}

}

/* 获取数据库连接的函数*/

private static Connection getConnection() {

Connection con = null; //创建用于连接数据库的Connection对象

try {

Class.forName(bundle.getString("db.classname"));// 加载Mysql数据驱动

con = DriverManager.getConnection(bundle.getString("db.url"), bundle.getString("db.username"), bundle.getString("db.password"));// 创建数据连接

} catch (Exception e) {

System.out.println("数据库连接失败" + e.getMessage());

}

return con; //返回所建立的数据库连接

}

/**

* 判断表是否存在

* @param tabName

* @return

*/

public static boolean exitTable(String tabName){

boolean flag = false;

conn = getConnection(); // 首先要获取连接,即连接到数据库

try {

String sql = "select id from "+tabName+";";

//预处理SQL 防止注入

ps = conn.prepareStatement(sql);

//执行

flag = ps.execute();

//关闭流

ps.close();

conn.close(); //关闭数据库连接

} catch (SQLException e) {

System.out.println("删除数据失败" + e.getMessage());

}

return flag;

}

/**

* 删除数据表

* 如果执行成功则返回false

* @param tabName

* @return

*/

public static boolean dropTable(String tabName){

boolean flag = true;

conn = getConnection(); // 首先要获取连接,即连接到数据库

try {

String sql = "drop table "+tabName+";";

//预处理SQL 防止注入

ps = conn.prepareStatement(sql);

//执行

flag = ps.execute();

//关闭流

ps.close();

conn.close(); //关闭数据库连接

} catch (SQLException e) {

System.out.println("删除数据失败" + e.getMessage());

}

return flag;

}

/**

* 测试方法

* @param args

*/

public static void main(String[] args) {

//建表===========================================

//表名

// String tabName = "mytable";

//表字段

// String[] tab_fields = {"name","password","sex","age"};

//创建表

// createTable(tabName, tab_fields);

//添加===========================================

//模拟数据

// String[] data1 = {"jack","123456","男","25"};

// String[] data2 = {"tom","456789","女","20"};

// String[] data3 = {"mark","aaa","哈哈","21"};

//插入数据

// insert(tabName, tab_fields, data1);

// insert(tabName, tab_fields, data2);

// insert(tabName, tab_fields, data3);

//查询=============================================

// String[] q_fileds ={"name","sex"};

// String[] data4 = {"jack","男"};

//

// String[] result = query(tabName, q_fileds, data4, tab_fields);

// for (String string : result) {

// System.out.println("结果:\\t"+string);

// }

//删除 清空=============================================

// delete(tabName);

//是否存在

// System.out.println(exitTable("mytable"));

//删除表

// System.out.println(dropTable("mytable"));

}

}

数据库的配置文件 db.properties

?

1

2

3

4
db.username=root

db.password=root

db.classname=com.mysql.jdbc.Driver

db.url = jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull

希望本文所述对大家java程序设计有所帮助。

原文链接:http://blog.csdn.net/lovelong8808/article/details/44077521

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

快网idc优惠网 建站教程 java使用JDBC动态创建数据表及SQL预处理的方法 https://www.kuaiidc.com/115376.html

相关文章

发表评论
暂无评论