-7

我想在 java 中创建包含两列的 MySQL 表,列的名称由用户输入?

4

2 回答 2

2

首先你必须连接到数据库,然后你可以执行查询:

 System.out.println("Table Creation Example!");
 Connection con = null;
 String url = "jdbc:mysql://localhost:3306/";
 String dbName = "jdbctutorial";
 String driverName = "com.mysql.jdbc.Driver";
 String userName = "root";
 String password = "root";
 String column1 = "nameOfTheFirstColumn";
 String column2 = "nameOfTheSecondColumn";

 try{
  Class.forName(driverName).newInstance();
 con = DriverManager.getConnection(url+dbName, userName, password);
 try{
  Statement st = con.createStatement();
  String table = 
  "CREATE TABLE Employee11(column1 + " varchar(10), + column2 + "Emp_name varchar(10))";
  st.executeUpdate(table);
  System.out.println("Table creation process successfully!");
  }
  catch(SQLException s){
  System.out.println("Table all ready exists!");
  }
  con.close();
  }
  catch (Exception e){
  e.printStackTrace();
  }

改编自此来源

于 2013-04-16T00:46:48.403 回答
0

首先使用Scanner. 现在用这些列名创建表

  Statement statement = connection.createStatement();
  String createTable = 
  "CREATE TABLE NEWTABLE(" + inputName1 + "varchar(100), " + inputName2 + " varchar(100))";
  statement.executeUpdate(createTable);
于 2013-04-16T00:52:29.177 回答