Java uses executeupdate to create tables in the database
1. Create the mysql. ini file and configure it as follows:
Driver = com. MySQL. JDBC. driverurl = JDBC: mysql: // 127.0.0.1: 3306/select_testuser = rootpass = 123456
In this way, you can directly modify the database configuration in the mysql. ini file.
2. WriteCode
Initparam method: obtain data in MySQL. ini.
Createtale method: connect to the database and execute the SQL statement executeupdate. In this example, the SQL file is the table creation statement.
Main method: input an SQL statement.
Class executeddl {private string driver; private string URL; private string user; private string pass; connection conn; statement stmt; Public void initparam (string paramfile) throws exception {properties props = new properties (); props. load (New fileinputstream (paramfile); driver = props. getproperty ("driver"); url = props. getproperty ("url"); User = props. getproperty ("user"); pass = props. getproperty ("pass ");} Public void createtale (string SQL) throws exception {try {class. forname (driver); Conn = drivermanager. getconnection (URL, user, pass); stmt = Conn. createstatement (); stmt.exe cuteupdate (SQL);} finally {If (stmt! = NULL) {stmt. Close ();} If (Conn! = NULL) {Conn. close () ;}}/*** @ Param ARGs * @ throws exception */public static void main (string [] ARGs) throws exception {// todo auto-generated method stubexecuteddl ED = new executeddl (); ed. initparam ("src/MySQL. ini "); ed. createtale ("create table student" + "(ID int," + "name varchar (50)," + "Num varchar (20)"); system. out. println ("creating Table success! ");}
Note: It is best to pass the passed SQL statement in MySQL, and the path of the input mysql.int file must be correct.
After the execution is complete, check whether the student table has been created successfully in the select_test database of MySQL.
3. Use the executeupdate method to insert data into the table.
Change the SQL statement used to create a table to the statement used to insert a data table and execute the executeupdate method. The result is that you want to insert data into the table.
Create an insertsql variable.
Private Static string insertsql = "insert into student values (1, 'xiaoming', '123 ')";
Execute the insert statement.
Ed. createtale (insertsql );
Other codes are the same.