I used mySQL workbench to create a database named testdb. Then I connect to it by Database>Connect to Database. Then I write some code in java (eclipse) to
The output of code shows that the connection and create table is done.
But When I return to mySQL, I don't see any table in the database. Can anyone help me about why table isn't created?
package database;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
public class main {
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
getConnection();
createTable();
}
public static void createTable() throws Exception {
try {
Connection con = getConnection();
PreparedStatement create = con.prepareStatement("CREATE TABLE IF NOT EXISTS tablename(id int NOT NULL AUTO_INCREMENT, first varchar(255), last varchar(255), PRIMARY KEY(id)");
create.executeUpdate();
}catch(Exception e) {System.out.println(e);}
finally {
System.out.println("Function complete.");
};
}
public static Connection getConnection() throws Exception{
try {
String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost:3306/testdb";
String username = "root";
String password = "00000";
Class.forName(driver);
Connection conn = DriverManager.getConnection(url, username, password);
System.out.println("Connected");
return conn;
} catch(Exception e) {System.out.println(e);}
return null;
}
}
Here is the output:
Connected
Connected
java.sql.SQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 1
Function complete.
您的sql语句中缺少括号)
,正确的是
"CREATE TABLE IF NOT EXISTS tablename(id int NOT NULL AUTO_INCREMENT, first varchar(255), last varchar(255), PRIMARY KEY(id))"
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.