Denne artikel indeholder et java-eksempel på, hvordan du bruger java.sql. Statement for at udføre oprette MySQL-tabel SQL-scripts.
1. JDBC Statement Code Snippets
- Kildekoden nedenfor for java-uddrag viser, hvordan du opretter java.sql.Connection objekt og opret java.sql. Statement objekt og kør et SQL-script gennem java.sql.Statement objekt.
/* Get mysql connection object.*/ java.sql.Connection conn = this.getMySqlConnection(ip, port, dbName, userName, password); if(conn!=null) { /* Create Statement object. */ java.sql.Statement stmt = conn.createStatement(); /* Execute create table sql command. */ stmt.execute(createTableSql); }
2. Fuldfør Java-kode
- StatementCreateTableExample.java
public class StatementCreateTableExample { public static void main(String[] args) { StatementCreateTableExample scte = new StatementCreateTableExample(); /* This is the sql command to create mysql table. */ String createMySqlTableSql = "CREATE TABLE `test`.`teacher` ( `name` VARCHAR(100) NOT NULL , `email` VARCHAR(100) NOT NULL ) ENGINE = InnoDB; "; scte.createMySQLTable("localhost", 3306, "test", "root", "", createMySqlTableSql); } /* This method return java.sql.Connection object from MySQL server. */ public Connection getMySqlConnection(String ip, int port, String dbName, String userName, String password) { /* Declare and initialize a sql Connection variable. */ Connection ret = null; try { /* Register for mysql jdbc driver class. */ Class.forName("com.mysql.jdbc.Driver"); /* Create mysql connection url. */ String mysqlConnUrl = "jdbc:mysql://" + ip + ":" + port + "/" + dbName; /* Get the mysql Connection object. */ ret = DriverManager.getConnection(mysqlConnUrl, userName , password); }catch(Exception ex) { ex.printStackTrace(); }finally { return ret; } } public void createMySQLTable(String ip, int port, String dbName, String userName, String password, String createTableSql) { Connection conn = null; Statement stmt = null; try { /* Get mysql connection object.*/ conn = this.getMySqlConnection(ip, port, dbName, userName, password); if(conn!=null) { /* Create Statement object. */ stmt = conn.createStatement(); /* Execute create table sql command. */ stmt.execute(createTableSql); } }catch(Exception ex) { ex.printStackTrace(); }finally { /* Release statment and connection object. This can save system resources. */ try { if(stmt!=null) { stmt.close(); stmt = null; } if(conn!=null) { conn.close(); conn = null; } }catch(Exception ex) { ex.printStackTrace(); } } } }
3. Udførelsesresultat.
- Når kodeudførelsen er færdig, kan du se, at tabellen lærer er blevet oprettet under MySQL testdatabasen.
- Du kan læse artiklen Sådan bruges JDBC til at forbinde MySql-database for at lære mere om MySQL JDBC-drift.