我有一个新的疑问。我想在macfast数据库中创建一个名为admin的表。该表创建成功,但是当我以手动方式插入值(使用查询)时,它似乎是一个错误。我的代码如下
public void createTableAdmin() {
try{
Class.forName("com.mysql.jdbc.Driver");
conn = (Connection) DriverManager.getConnection(DB_URL_table, USER, PASS);
stmt = (Statement) conn.createStatement();
String sql1 = "CREATE TABLE IF NOT EXISTS admin " +
"(id INTEGER not NULL, " +
" user_name VARCHAR(255), " +
" password VARCHAR(255), " +
" isAdmin BOOLEAN NOT NULL DEFAULT '0', " +
" PRIMARY KEY ( id ))";
stmt.executeUpdate(sql1);
String insert="INSERT INTO admin(id,user_name,password,isAdmin)VALUES(1,admin,admin,1)";
stmt.executeUpdate(insert);
}catch(SQLException se){
//Handle errors for JDBC
se.printStackTrace();
}catch(Exception e){
//Handle errors for Class.forName
e.printStackTrace();
}finally{
//finally block used to close resources
try{
if(stmt!=null)
conn.close();
}catch(SQLException se){
}// do nothing
try{
if(conn!=null)
conn.close();
}catch(SQLException se){
se.printStackTrace();
}//end finally try
}//end try
}
错误类似于
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown column 'admin' in 'field list'
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
答案 0 :(得分:3)
''
列值附近缺少引号VARCHAR
。
String insert = "INSERT INTO admin (id,user_name,password,isAdmin) " +
"VALUES (1, 'admin', 'admin', 1)";
答案 1 :(得分:3)
您没有正确引用字符串;
String insert=
"INSERT INTO admin(id,user_name,password,isAdmin)VALUES(1,admin,admin,1)";
应该是
String insert=
"INSERT INTO admin(id,user_name,password,isAdmin)VALUES(1,'admin','admin',1)";
答案 2 :(得分:0)
您的值需要引号,或者它们被视为字段名称。
public void createTableAdmin(){ 尝试{
Class.forName("com.mysql.jdbc.Driver");
conn = (Connection) DriverManager.getConnection(DB_URL_table, USER, PASS);
stmt = (Statement) conn.createStatement();
String sql1 = "CREATE TABLE IF NOT EXISTS admin " +
"(id INTEGER not NULL, " +
" user_name VARCHAR(255), " +
" password VARCHAR(255), " +
" isAdmin BOOLEAN NOT NULL DEFAULT '0', " +
" PRIMARY KEY ( id ))";
stmt.executeUpdate(sql1);
String insert="INSERT INTO admin(id,user_name,password,isAdmin)VALUES(1,'admin','admin',1)";
stmt.executeUpdate(insert);
}catch(SQLException se){
//Handle errors for JDBC
se.printStackTrace();
}catch(Exception e){
//Handle errors for Class.forName
e.printStackTrace();
}finally{
//finally block used to close resources
try{
if(stmt!=null)
conn.close();
}catch(SQLException se){
}// do nothing
try{
if(conn!=null)
conn.close();
}catch(SQLException se){
se.printStackTrace();
}//end finally try
} //结束尝试
}