本次介绍一下java后台对的数据库的操作。在此,我们接收到的数据是前端数据传来的json字符串,因此本文讲述的便是使用json字符串来对数据库的增删改查 (PS:本文中所运用的开发软件是IDEA) 菜鸡自学心得总结,有不对的地方请指出,谢谢!
先上代码
//新建数据表函数 public static void createTable(JSONObject jsonObject) throws SQLException { Connection conn = null; String sql,sqll; sql = "create table "; sqll = "(id integer not null AUTO_INCREMENT,primary key(id), lastUpdated date null,dateCreated date null,"; Iterator it = jsonObject.keys(); while (it.hasNext()){ //sql += it.next().toString()=="name"?jsonObject.getString(it.next().toString())+ "( id int PRIMARY KEY not null auto_increment , lastUpdated date null,dateCreated date null,":it.next().toString()+" "+jsonObject.getString(it.next().toString())+","; String key = it.next().toString(); String value = jsonObject.getString(key); if(key .equals("name") ){ sql+=jsonObject.getString(key)+sqll; }else{ sql+=key + " " + value +","; } } sql = sql.substring(0,sql.length()-1)+")"; System.out.println(sql); String url = "jdbc:mysql://* * * * * 数据库主机名* * * * /* * *数据库名 * * * * ?" + "user=gTest&password=123456&useUnicode=true&characterEncoding=UTF8"; //各类参数和其值 try { Class.forName("com.mysql.jdbc.Driver");// 动态加载mysql驱动 System.out.println("成功加载MySQL驱动程序"); // 一个Connection代表一个数据库连接 conn = DriverManager.getConnection(url); // Statement里面带有很多方法,比如executeUpdate可以实现插入,更新和删除等 Statement stmt = conn.createStatement(); //sql = "create table student(NO INTEGER not NULL AUTO_INCREMENT ,primary key(NO), name varchar(20))"; int result = stmt.executeUpdate(sql);// executeUpdate语句会返回一个受影响的行数,如果返回-1就没有成功 if (result != -1) { System.out.println("创建数据表成功"); } } catch (SQLException e) { System.out.println("MySQL操作错误"); e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } finally { conn.close(); } }其实不难看出,这种方法其实就是使用字符串,将json中有用的参数拼接成sql语句在对数据库进行操作(sql语句不会的可以参照w3school、菜鸟教程等网站)。
这里则是运用迭代器,提取出json中所需要的元素进行sql语句的拼接(json数据其实就类似于hashmap的键值对)。
最后则是加载mysql驱动,连接数据库,以及数据库的操作和错误的捕捉