I've got a database set up to store notes. I want to auto increment the first column. I've tried this, but when I read from the database every result in that column is 'null'.This is the code for creating the DB.
private static final String NOTES_TABLE_CREATE =
"CREATE TABLE " + NOTES_TABLE_NAME + " (" +
COLUMN_NAMES[0] + " INTEGER AUTO_INCREMENT, " +
COLUMN_NAMES[1] + " TEXT, " +
COLUMN_NAMES[2] + " TEXT, " +
COLUMN_NAMES[3] + " TEXT, " +
COLUMN_NAMES[4] + " TEXT, " +
COLUMN_NAMES[5] + " TEXT, " +
COLUMN_NAMES[6] + " TEXT);";
This is the code for getting the DB result.
SQLiteDatabase db = this.getReadableDatabase();
Cursor result = db.query(NOTES_TABLE_NAME, COLUMN_NAMES, null, null, null, null, null, null);
result.moveToFirst();
result.moveToNext();
System.out.println(result.getInt(0));
System.out.println(result.getString(1));
This is the output from logcat
04-09 17:56:17.981 22147-22147/com.example.a8460p.locationotes I/System.out: 0
04-09 17:56:17.981 22147-22147/com.example.a8460p.locationotes I/System.out: notetitle1234567890
AUTO_INCREMENT (as opposed to INTEGER PRIMARY KEY AUTOINCREMENT) is not supported in sqlite.
This is a little non-obvious, because sqlite silently ignores column constraints it does not recognize:
sqlite> CREATE TABLE test (
a INTEGER FABBELBABBEL NOT NULL
);
sqlite> .schema test
CREATE TABLE test (a INTEGER FABBELBABBEL NOT NULL);
sqlite> INSERT INTO test (a) VALUES (1);
sqlite> INSERT INTO test (a) VALUES (NULL);
Error: NOT NULL constraint failed: test.a
AUTOINCREMENT on the other hand, is supported for integer primary keys and only there, so the obvious workaround attempt is not supported, either:
sqlite> CREATE TABLE test (a INTEGER AUTOINCREMENT NOT NULL, b INTEGER);
Error: near "AUTOINCREMENT": syntax error
In short: Auto increment is only available for integer primary keys.
Related
INSERT OR REPLACE works when there is only one row in the table and it happens to be the one that is replaced. However, when there are multiple rows in the table, INSERT OR REPLACE just inserts and creates a duplicate!
For example, if I create an entry with eventId = '123'. And then try to write another entry with eventId = '123' and roomnumber equal to something different than the first entry, INSERT OR REPLACE will work. However, if there are more than one rows in the table it will create a duplicate. Here is my code:
String createSql = "CREATE TABLE IF NOT EXISTS events (\n"
+ " eventId VARCHAR(20) PRIMARY KEY ON CONFLICT REPLACE,\n"
+ " roomNumber VARCHAR(20) NOT NULL,\n"
+ " startTime TIMESTAMP NOT NULL,\n"
+ " endTime TIMESTAMP NOT NULL,\n"
+ " name VARCHAR(250),\n"
+ " isVIP BOOLEAN NOT NULL,\n"
+ " capacity INTEGER(20) NOT NULL, \n"
+ " UNIQUE (eventId) \n"
+ ");";
String sql = "INSERT OR REPLACE INTO events (eventId, roomNumber, startTime, endTime, capacity, name, isVIP)" + " Values('"+event.getID()+"', '"+event.getRoomNumber()+"', '"+event.getStartTime()+"', '"+event.getEndTime()+"', '"+event.getCapacity()+"', '"+event.getName()+"', '"+event.getVIPStatus()+"')";
I would read this thread for more information about how REPLACE works.
https://stackoverflow.com/questions/29539838/replace-versus-insert-in-sql#:~:text=According%20to%20the%20documentation%2C%20the,the%20new%20row%20is%20inserted.
Also I would suggest trying just "REPLACE," as it functions as INSERT but will replace on conflicts.
i need a tip here , here i have a code to insert into sqlite database:
Thread t = new Thread(new Runnable() {
#Override
public void run() {
String sqlCreate = "CREATE TABLE IF NOT EXISTS " + name
+ " (ID INTEGER PRIMARY KEY AUTOINCREMENT,"
+ " Type TEXT,"
+ " Text TEXT,"
+ " OtherFormats TEXT,"
+ " Date TEXT,"
+ " Image TEXT,"
+ " RealName TEXT)";
db.execSQL(sqlCreate);
//(String Type, String Text ,String name,String OtherFormats,String Itime,String
RealName)
String sqlInsert= "INSERT INTO " + "'"+name+"'" +
" VALUES
("+"'"+ID+"'"+","+"'"+Type+"'"+","+"'"+Text+"'"+","+
"'"+OtherFormats+"'"+","+"'"+Date+"'"+"
,"+"'"+Image+"'"+","+"'"+RealName+"')";
db.execSQL(sqlInsert);
}
});
t.start();
the question is as you u see my ID is auto increment, but for executing it well, i need to put a value there,what value should i put so it database does the increament itself?
thanks
05-26 03:56:33.018: E/AndroidRuntime(23809):
android.database.sqlite.SQLiteException: near "VALUES": syntax error (code 1): ,
while compiling: INSERT INTO 'new' (Type,Text,OtherFormats ,Date,Image,RealName VALUES('m','hey','n','03:56','j','s')
You can do this. Enter the name of columns you need to insert
String sqlInsert= "INSERT INTO " + "'"+name+"' (Type,Text,OtherFormats ,Date,Image,RealName )VALUES
("+"'"+ID+"'"+","+"'"+Type+"'"+","+"'"+Text+"'"+","+
"'"+OtherFormats+"'"+","+"'"+Date+"'"+"
,"+"'"+Image+"'"+","+"'"+RealName+"')";
db.execSQL(sqlInsert);
the question is as you u see my ID is auto increment, but for executing it well, i need to put a value there,what value should i put so it database does the increament itself?
Put in a NULL or just leave it unspecified.
From the documentation:
If no ROWID is specified on the insert, or if the specified ROWID has a value of NULL, then an appropriate ROWID is created automatically.
I am using oracle 10g and I wrote a create table query like this -
String UserTable="CREATE TABLE UserDetail ( \n" +
" idNo INT(64) NOT NULL , \n" +
" name VARCHAR(50),\n" +
" email VARCHAR(50), \n" +
" state VARCHAR(50),\n"+
" country VARCHAR(50),\n" +
" CONSTRAINT person_pk PRIMARY KEY ('idNo')"
+ ");";
// Connection con2=DriverManager.getConnection(DbAddress,"vivek","123456");
PreparedStatement st2=conn.prepareStatement(UserTable);
st2.executeUpdate();
conn.close();
but it gives following exception-
java.sql.SQLSyntaxErrorException: ORA-00907: missing right parenthesis
on syssout it the query becomes this -
CREATE TABLE UserDetail (
idNo INT(64) NOT NULL ,
name VARCHAR(50),
email VARCHAR(50),
state VARCHAR(50),
country VARCHAR(50),
CONSTRAINT person_pk PRIMARY KEY (idNo)
);
please help.
Remove the below line
CONSTRAINT person_pk PRIMARY KEY ('idNo')
Use the below line in your code instead
CONSTRAINT person_pk PRIMARY KEY (idNo)
oh I got the solution- I was using Int instead of Number and it was not supported. the query should be-
"CREATE TABLE UserDetail ( \n" +
" idNo NUMBER NOT NULL , \n" +
" name VARCHAR(50),\n" +
" email VARCHAR(50), \n" +
" state VARCHAR(50),\n"+
" country VARCHAR(50),\n" +
" CONSTRAINT person_pk PRIMARY KEY ('idNo')"
+ ");";
I'm trying to create a table similar to a ready table I created before (a template, if you will) where the only variable should be the table name.
This is what I've tried so far:
I exported the template table to mysql code and copied the code to a preparedStatement object as such:
createNewLineTableStatement = constantLink.prepareStatement("CREATE TABLE IF NOT EXISTS ? (" +
" `index` int(5) NOT NULL," +
" `station` int(5) NOT NULL," +
" PRIMARY KEY (`index`)," +
" UNIQUE KEY `station` (`station`)" +
") ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;\");");
Than I try to execute the code by calling the following function:
private static boolean createNewLineTable(String tableName) throws SQLException{
createNewLineTableStatement.setString(1, tableName);
if (createNewLineTableStatement.executeUpdate() == Statement.EXECUTE_FAILED)
return false;
return true;
}
But I'm getting a syntax error exception:
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 ''line_37_var_1' ( `index` int(5) NOT NULL, `station` int(5) NOT NULL, PRIMARY' at line 1
How can I fix the code? OR is there a cleaner, better way to do the same thing? Maybe creating a script with a user variable? I thought of that but I've never used .sql script before.
Problem 1: You can't use a prepared statement parameter as the table name.
Problem 2: You have an unmatched paren and extra characters ");at the end of your statement.
Your query string should look something like:
String query = "CREATE TABLE IF NOT EXISTS `" + tableName + "` (" +
" `index` int(5) NOT NULL," +
" `station` int(5) NOT NULL," +
" PRIMARY KEY (`index`)," +
" UNIQUE KEY `station` (`station`)" +
") ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci";
by design, TableName and ColumnNames cannot be parameterized.
If you are scared about SQL Injection, create a custom function to check for malicious tableName. It is safe if the value comes inside of your application.
Then concatenate it in the string, add backtick for first level of defense :D
String tableName = "Your tableName";
String query = "CREATE TABLE IF NOT EXISTS `" + tableName + "` (" +
" `index` int(5) NOT NULL," +
" `station` int(5) NOT NULL," +
" PRIMARY KEY (`index`)," +
" UNIQUE KEY `station` (`station`)" +
") ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci";
You are missing Table name and i think that "?" shouldn't be there.
I will be something like
"CREATE TABLE IF NOT EXISTS YOURTABLE" + the following code
when i create column family using the cql it gives me very unexpected output.
public static void createColumnfamily()
{
try
{
Class.forName("org.apache.cassandra.cql.jdbc.CassandraDriver");
Connection con = DriverManager.getConnection("jdbc:cassandra://192.168.1.32:9160/temp");
String qry = "CREATE TABLE users(user_name varchar," +
"password varchar," +
"gender varchar," +
"session_token varchar," +
"birth_year bigint," +
"PRIMARY KEY (user_name)" +
")";
Statement smt = con.createStatement();
smt.executeUpdate(qry);
System.out.println("TABLE(column family) is created");
con.close();
}
catch(Exception e)
{
System.out.println(" : " + e.getMessage());
}
}
Here what i got : line 1:132 extraneous input ')' expecting EOF
You're using CQL 2, which does not support that style of primary key declaration. If you want to declare it that way, you should be using CQL 3, which you can accomplish by requesting that version in the connection URL:
DriverManager.getConnection("jdbc:cassandra://192.168.1.32:9160/temp?version=3.0.0");
However, CQL 3 isn't necessary just for this. As Steve Van Opstal suggested, you can simply put the PRIMARY KEY marker with the column definition itself, since you don't have a multi-component primary key.
CREATE TABLE users(
user_name varchar PRIMARY KEY,
password varchar,
gender varchar,
session_token varchar,
birth_year bigint,
);
CQL 3 is to be generally preferred if your Cassandra supports it, as it is the way forward, but in case you don't want to switch right now, you can make that second change.
I only see two possible problems here.
The query doesn't accept your way of defining the primary key
Try this:
String qry = "CREATE TABLE users(user_name varchar PRIMARY KEY," +
"password varchar," +
"gender varchar," +
"session_token varchar," +
"birth_year bigint"
")";
The query doesn't accept varchar's as primary key
Try this:
String qry = "CREATE TABLE users(user_id int" +
"user_name varchar," +
"password varchar," +
"gender varchar," +
"session_token varchar," +
"birth_year bigint," +
"PRIMARY KEY (user_id)" +
")";