Home > Back-end > Inserted into the database API access json format data??
Inserted into the database API access json format data??
Time:12-23
The json data in the console
After formatting is
How do these console json data save to the database? O bosses know!!!!!!
CodePudding user response:
Can you get these data first, and then parsed into corresponding entity objects to the background, and save to the database is not line
CodePudding user response:
1. You first introduce corresponding database jar package, for example, I am a MySQL will introduce the MySQL connection - Java 2. The following code can create MySQL link, if you are other database, only to do is according to the comments I change
The import com. Google. Gson. Gson; Import the Java. SQL. Connection; Import the Java. SQL. DriverManager; Import of Java, SQL PreparedStatement; Import the Java. SQL. SQLException; import java.util.HashMap; import java.util.Map;
Public static void main (String [] args) { Try { /* * built predicate sentence * CREATE TABLE ` test ` ( * ` id ` int the NOT NULL AUTO_INCREMENT, * ` json_text ` text COLLATE utf8mb4_bin, * PRIMARY KEY (` id `) *) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin; */ Class.forname (". Com. Mysql. Cj. JDBC Driver "); The String url="JDBC: mysql://localhost: 3306/firm ssy";//if it is other databases, you just need to change the MySQL database for other String user="root"; String password="XXX"; The Connection Connection=DriverManager. GetConnection (url, user, password); String SQL="INSERT INTO ` test ` (json_text) VALUES (?) "; PreparedStatement ps=connection. PrepareStatement (SQL); Map The map=new HashMap<> (a); The map. The put (" id ", "1"); The map. The put (" name ", "sunsy"); Ps. SetString (1, new Gson (). The toJson (map)); Ps. The execute (); } the catch (a ClassNotFoundException e) { e.printStackTrace(); {} the catch (SQLException throwables) Throwables. PrintStackTrace (); } }
CodePudding user response:
The result is the Id json_test 1 {" name ":" sunsy ", "id" : "1"}