Failed to create table with SQLite - java

I'm trying to create a table with a list of names in it. This outputs:
"Failed to create table_name"
It was working before, I'm using Netbeans IDE with SQLite 3.7.2. I've also tried executing statements on the database which works fine. But it won't work through the Java code below
class DatabaseHelper{
public void addToDb(String tbname, List<String> name){
try {
String url = "jdbc:sqlite:D:/names.db";
Class.forName("org.sqlite.JDBC");
try(Connection conn = DriverManager.getConnection(url);
Statement stmt = conn.createStatement();){
stmt.execute("CREATE TABLE IF NOT EXISTS " + tbname + "(id integer PRIMARY KEY AUTOINCREMENT,"
+ "name text NOT NULL)");
name.forEach((s) -> {
try{
stmt.execute("INSERT INTO " + tbname + "(name) VALUES('" + s + "')");
}catch(SQLException e){
e.printStackTrace();
}
});
System.out.println("Finished");
}catch(SQLException e){
e.printStackTrace();
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
EDIT : It does works, only takes to refresh it. No actual problems it seems

Try to create your table with a database name like this :
String query = "CREATE TABLE IF NOT EXISTS databasename." + tbname +
" (id integer PRIMARY KEY AUTOINCREMENT, name text NOT NULL)";
If your database already contain schema then create your table with schema name like this :
CREATE TABLE [IF NOT EXISTS] [schema_name].table_name (
so :
String query = "CREATE TABLE IF NOT EXISTS sch_name." + tbname +
" (id integer PRIMARY KEY AUTOINCREMENT, name text NOT NULL)";
You can learn more here : SQLite Create Table
Ooops this is logic
This error is logic it return false all the time, if you try st.executeUpdate(q) and your query is success it will return 0 because CREATE TABLE does not return any thing for that you get negative result all the time, not like Insert or Update it return a result when you execute your statement, so i suggest to change your code to this :
boolean created;
try {
q = "CREATE TABLE ...";
Statement st = connection.createStatement();
//you can use
System.out.println(st.executeUpdate(q));
//or
System.out.println(st.execute(q));
created = true;
} catch (SQLException e) {
created = false;
}
//now you can check if your table is created or not
if(created){
System.out.println("Table created with sucess");
}else{
System.out.println("Faild to create table");
}
Hope this work with you.

if(stmt.execute("CREATE TABLE IF NOT EXISTS " + tbname + ";"+"CREATE TABLE "+ tbname + "(id integer PRIMARY KEY AUTOINCREMENT,"
+ "name text NOT NULL)"))
or can you give the exception that was raised

Related

MySQL checking if a entry is set

Im trying to check if a entry is set, so for example in a row with: user, password, birth
I check if in column user f.e. "mxrlin" is
For that im using that code in my Main Class:
if(!mySQL.isSet(tableName, "houseNumber", houseNumberStr)){
System.out.println(house.getHouseNumber() + " not set yet");
inserts.add(new BetterMySQL.KeyValue("houseNumber", houseNumberStr));
mySQL.insertEntry(tableName, inserts);
}else {
System.out.println(house.getHouseNumber() + " set -> updating");
mySQL.update(tableName, inserts, "houseNumber", houseNumberStr);
}
And the mySQL.isSet() method looks like this:
public boolean isSet(String tableName, String key, String value){
Check.checkNotEmpty(tableName);
Check.checkNotEmpty(key);
Check.checkNotEmpty(value);
ResultSet resultSet = MySQL.getResultSetPrepareStatement(connection, "SELECT * FROM " + tableName + " WHERE ?=?", Arrays.asList(key, value));
try {
if(resultSet.next()){
return resultSet.getObject(value) != null;
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
resultSet.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
return false;
}
But with this code it always debugs me "house.getHouseNumber() + " not set yet", so the Class doesnt find the entry that is set
You can't bind a parameter to a column name. The key in this case will be treated as a string literal in SQL.
Assuming a method call like this:
mySQL.isSet("houses", "houseNumber", "2335")
this code:
ResultSet resultSet = MySQL.getResultSetPrepareStatement(connection, "SELECT * FROM " + tableName + " WHERE ?=?", Arrays.asList(key, value));
Will generate a SQL statement equivalent to
SELECT * FROM houses WHERE 'houseNumber'='2335'
Of course, the string 'houseNumber' will never equal the string '2335', so no results will be returned.
You'll need to substitute key into the SQL string, just like tableName already is:
ResultSet resultSet = MySQL.getResultSetPrepareStatement(connection, "SELECT * FROM " + tableName + " WHERE " + key + "=?", Arrays.asList(value));

MySQL table not visible in Workbench

I executed the below code to create a table USER and everything looks fine since when I try to execute it again, I get the error "Table 'USER' already exists".
public static void main(String[] args) throws SQLException, ClassNotFoundException {
sqlDB mysqlConnect = new sqlDB();
Statement stmt = mysqlConnect.connect().createStatement();
String sql = "CREATE TABLE USER " +
"(id INTEGER not NULL, " +
" first VARCHAR(255), " +
" last VARCHAR(255), " +
" PRIMARY KEY ( id ))";
try {
stmt.executeUpdate(sql);
PreparedStatement statement = mysqlConnect.connect().prepareStatement(sql);
} catch (SQLException e) {
e.printStackTrace();
} finally {
mysqlConnect.disconnect();
}
}
My question is why don't I see this table in MySQL Workbench?
I checked the section 'Schemas' but there I have only 1 db 'sys' which is not the one I created.
User is a mysql system table;
You can create a new db and create the table new db.Tablename;

servlet init method fails to create mysql tables - why?

my java servlet init method fails to create mysql tables - I'd like to know why. When I log on to mysql directly and create the tables life is beautiful, when I delete the tables and run the servlet - no tables, servlet throws an exception (haven't quite dug that up yet).The code looks like this:
package ...;
import ... // quite a bit
#WebServlet("/MyClass")
public class MyClass extends HttpServlet {
public void init() throws ServletException {
try { Foo foo = Foo.getInstance();
foo.createTables();
} catch (Exception e) {
throw new ServletException("Error creating tables", e);
}
}
... // more MyClass stuff
}
//Foo is a singleton that looks like this:
package ...;
import ... // quite a bit
public class Foo {
public static final Foo INSTANCE = new Foo();
public static Foo getInstance() {
return INSTANCE;
}
... // more Foo stuff, then
public void createTables(){
try {
// first establish a connection
Connection connection = Foo.getInstance().getConnection(); // get connection est.
// est. connection to dbase - works well once the tables are set up
//Create a query.
Statement stmt = connection.createStatement();
String query = "CREATE TABLE IF NOT EXISTS survey (uuid_Survey VARCHAR(36) NOT NULL, "+
"top VARCHAR(40), " +
" likert VARCHAR(40), "+
" numerical VARCHAR(40), "+
" open VARCHAR(40), " +
" KEY ix_survey_uuid (uuid_Survey), "+
" PRIMARY KEY (uuid_Survey))";
ResultSet rs = stmt.executeQuery( query );
query = "CREATE TABLE IF NOT EXISTS result (" +
"uuid_Survey VARCHAR(36) NOT NULL, "+
"remoteAddress VARCHAR(15) NOT NULL, " +
"currentTime BIGINT NOT NULL, "+
" likert VARCHAR(40),"+
" numerical DOUBLE, " +
" open VARCHAR(40), "+
" PRIMARY KEY (uuid_Survey, remoteAddress, currentTime),"+
"FOREIGN KEY ix_survey_uuid (uuid_Survey) REFERENCES survey (uuid_Survey))" ;
rs = stmt.executeQuery( query );
connection.close();
} catch (Exception e) {
System.err.println("Error creating tables: " + e);
}
}
You cannot use stmt.executeQuery( query );
As the Doc says-
ResultSet#executeQuery(String sql) - This method executes the given SQL statement, which returns a single ResultSet object. where sql - an SQL statement to be sent to the database, typically a static SQL SELECT statement
You might want to use execute() instead
Like stmt.execute(query);
or
String query = "CREATE TABLE IF NOT EXISTS survey (uuid_Survey VARCHAR(36) NOT NULL,"+
"top VARCHAR(40), " +
" likert VARCHAR(40), "+
" numerical VARCHAR(40), "+
" open VARCHAR(40), " +
" KEY ix_survey_uuid (uuid_Survey), "+
" PRIMARY KEY (uuid_Survey))";
PreparedStatement statement = conn.prepareStatement(query);
int count = statement.executeUpdate();
if(count>=0){
System.out.println("Successfully created.");
}

SQL Syntax Error Creating Table

I am getting the following error when I try to create a table in an SQL database:
Failed to create table 'references'
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: 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 'references(referenceID BIGINT NOT NULL AUTO_INCREMENT,
referenceText VARCHAR(255)'
Here is the code making the table:
public void createReferencesTable() {
System.out.println("Creating table '" + REFERENCE_TABLE + "'...");
Statement stmt = null;
try {
stmt = connection.createStatement();
stmt.executeUpdate("CREATE TABLE " + REFERENCE_TABLE + "("
+ REFERENCE_ID + " BIGINT NOT NULL AUTO_INCREMENT,"
+ REFERENCE_TEXT + " VARCHAR(255),"
+ REFERENCE_TWEET + " BIGINT NOT NULL,"
+ "PRIMARY KEY (" + REFERENCE_ID + ")"
+ ")");
System.out.println("Table '" + REFERENCE_TABLE + "' created");
} catch (SQLException e) {
System.err.println("Failed to create table '" + REFERENCE_TABLE + "'");
e.printStackTrace();
} finally {
if (stmt != null) {
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
And here are the declarations of the variables used:
public static final String REFERENCE_TABLE = "references";
public static final String REFERENCE_ID = "referenceID";
public static final String REFERENCE_TEXT = "referenceText";
public static final String REFERENCE_TWEET = "referenceTweet";
Also, I am creating two tables before this one that successfully work with basically the exact same syntax as this one, which is failing. Also, the MySQL server I am putting this databases into is fresh and just set-up, so there shouldn't be any configuration issues, as my program is connecting to the database successfully.
My question is: Why is this giving an error?
Notes: I have tried to do the reference ID line with an identity, but that did not make any difference. As I said before, the two functions each creating a table before this used exactly the same syntax, but gave no errors and successfully created their tables.
references is a reserved word in MySQL. Either use backticks to escape it or use another name.
stmt.executeUpdate("CREATE TABLE `" + REFERENCE_TABLE + "` ("
^-----------------------^-----------here

not getting data into mysql from java

I'm not getting data into mysql
void connectionDB() {
try {
Class.forName(fileReader.getdriver());
String url = "jdbc:mysql://"+ fileReader.gethost() + ":" + fileReader.getDBport() +"/" + fileReader.getdbname();
conn = DriverManager.getConnection(url, fileReader.getusername(),fileReader.getpasswd());
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException se) {
se.printStackTrace();
}
}
public void snmp_mysql(String ipv6Address, String[] resString) {
try {
stat = conn.createStatement();
String sql =
("INSERT INTO Statistics3 VALUES ('" + ipv6Address + "','"
+ dateTime.trim() + "'," + battpercent + ")");
stat.executeUpdate(sql);
stat.close();
System.out.println("updating");
} catch (SQLException e) {
e.printStackTrace();
System.out.println("SQL statement is not executed!");
}
}
The code is not showing any error and it is showing Empty set (0.01 sec) in MySQL. Previously it worked properly and got the output. I didn't make any changes. I do not know why its not working.
I have taken another class in another project and added some columns to the existing table Statistics3,and used mysql for that class.I didnt make any changes in this class.That doesn't effect mysql know
While i'm running the project,i'm getting these errors in the middle of the output
java.sql.SQLException: Column count doesn't match value count at row 1
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1073)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3597)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3529)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1990)
You can explicitly specify the column into which you want to insert data.. As you can see, you can also skip some column..
String sql =
"INSERT INTO Statistics3 (column1, column2, column4) VALUES ('" + ipv6Address
+ "','" + dateTime.trim() + "'," + battpercent + ")";
column1, column2, and column4 are columns corresponding to your values - ipv6Address, datetime, and battpercent.. in your table..
So, if you have inserted a column - column3 , then you can just skip it.. It will get the default value as you have set..
added some columns to the existing table Statistics3
There is your problem. Number of values does not match with number of columns present.
You should use version of SQL statement
insert into table (col1,col2) values (val1,val2)
The values given in the insert query doesn't match with the columns in the DB. Make sure that you have values for all the columns(in your table) in your query.

Categories