import java.sql.*;
import java.util.Scanner;
public class DynamicTableCreate {
static String url, user, password;
static {
url="jdbc:mysql://localhost/testing";
user="root";
password="root";
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Connection con=null;
Statement stmt=null;
Scanner scan=new Scanner(System.in);
System.out.println("Enter table name");
String tname=scan.next();
System.out.println("Enter number of columns");
int cols=scan.nextInt();
System.out.println("Enter column names and data types ");
String [] colnames=new String[5];
String [] datatype=new String[5];
int i=0;
while(i<cols)
{
colnames[i]=scan.next();
datatype[i]=scan.next();
i++;
}
// Create table Trainers (T_Id int primary key, Trainer_name varchar(20), Stream varchar(20));
try {
Class.forName("com.mysql.jdbc.Driver");
con=DriverManager.getConnection(url,user,password);
stmt=con.createStatement();
String sql1 = "create table " + tname + "(" + colnames[0] + " " + datatype[0] + " primary key, ";
for(i=1;i<cols;i++)
{
sql1 += colnames[i] + " " + datatype[i] + ", ";
}
sql1+=");";
stmt.executeUpdate(sql1);
}
catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally
{
try
{
if (stmt!=null)
stmt.close();
if(con!=null)
con.close();
}
catch(Exception e)
{
}
}
}
}
我想创建一个表,其中用户提供表名,列数,列名及其数据类型,但我的代码抛出以下错误:
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException:你有 SQL语法中的错误;查看与您的手册相对应的手册 MySQL服务器版本,用于在第1行的')'附近使用正确的语法
解决方案是什么?
答案 0 :(得分:0)
问题解决了......
唯一要做的就是替换
sql1 += colnames[i] + " " + datatype[i] + ", ";
通过
sql1 += ", " + colnames[i] + " " + datatype[i];