我想在java中创建包含两列的MySQL表,其中列的名称由用户输入?
答案 0 :(得分: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();
}
改编自source。
答案 1 :(得分:0)
首先使用Scanner
获取列名称。现在用于创建具有这些列名称的表
Statement statement = connection.createStatement();
String createTable =
"CREATE TABLE NEWTABLE(" + inputName1 + "varchar(100), " + inputName2 + " varchar(100))";
statement.executeUpdate(createTable);