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)" +
")";
Related
I am trying to populate one table in my database with pretty complex data. For this, I am using a generator API (which gives me random data).
public void populateCrackers(){
PreparedStatement psm;
String queryJoke = "(SELECT jid FROM Jokes WHERE jid=?)";
String queryHat = "(SELECT hid FROM Hats WHERE hid=?)";
String queryGift = "(SELECT gid FROM Gifts WHERE gid=?)";
String query = "INSERT INTO Crackers(cid, name, jid, hid, gid, quantity) VALUES(" +
"?, " +
"?, " +
queryJoke + ", " +
queryHat + ", " +
queryGift + ", " +
"?)";
System.out.println(query);
String cracker_String = utils.JSONUtils.getJSON(crackerAPI, client);
JSONObject crackerJSON = new JSONObject(cracker_String);
JSONArray crackers = crackerJSON.getJSONArray("results");
for(int j=0; j<crackers.length(); j++){
try{
psm = connection.prepareStatement(query);
psm.setInt(1,crackers.getJSONObject(j).getInt("cid"));
psm.setString(2, crackers.getJSONObject(j).getString("cname"));
psm.setInt(3, crackers.getJSONObject(j).getInt("rjoke"));
psm.setInt(4, crackers.getJSONObject(j).getInt("rhat"));
psm.setInt(5, crackers.getJSONObject(j).getInt("rgift"));
psm.setInt(6, crackers.getJSONObject(j).getInt("cquantity"));
psm.execute();
System.out.println(crackers.getJSONObject(j).get("cid") + " "
+ crackers.getJSONObject(j).get("cname") + " "
+ crackers.getJSONObject(j).get("cquantity") + " "
+ crackers.getJSONObject(j).get("rjoke") + " "
+ crackers.getJSONObject(j).get("rhat") + " "
+ crackers.getJSONObject(j).get("rgift"));
}catch (Exception e){
e.printStackTrace();
}
}
}
This is the method that populates my "Crackers" tab. I am wondering if this be accepted as a prepared statement. When I run it in psql interactive command line tool, exactly that statement with some chosen ids (e.g INSERT INTO Crackers (cid, name, hid, jid, gid, quantity) VALUES('cid', 'name', (SELECT hid FROM Hats WHERE hid=11), (SELECT jid FROM Jokes where jid=99), (SELECT gid FROM Gifts WHERE gid=13), 5) it works flawlessly.
Does my preparedstatement break the Constraint?
Any ideas?
LATER EDIT: The inconsistency is the form of that null values can reach my Crackers table (e.g. Cracker(1, "hello", null, null, 3, 123) appears in the table.
There is nothing about Prepared statement. Constraint can be broken by parameters you set to it. And you can run your PLSQL statement as anonimous block in PreparedStatement as well.
Just surround it with BEGIN ... END. only one thing is different - for JDBC parameters are ? mark not :parameter as for PLSQL and there is no way to use named parameter.
That means if you need to use parameter more than once for JDBC you have to have that many ? marks and set all of them.
So, focus on parameters you pass to and their sequence.
The code is correct, though the prepared statement must be closed, and it would be better to create the statement once, before the for loop.
Now there is crackers.length() times a statement created but not closed. That might give problems.
Use the try-with-resouce syntax for automatic closing, irrespective of any exception or return.
try (PreparedStatement psm = connection.prepareStatement(query)) {
for (int j = 0; j < crackers.length(); j++) {
...
psm.executeUpdate();
And call executeUpdate instead of the more general execute. The resulting update count might be of interest (1/0).
I realised I had the wrong constraints on my table. I was letting null values in. There was nothing wrong with the prepared statement.
The right query to create the table is this one:
String createCrackersQuery = "CREATE TABLE Crackers(" +
" cid INTEGER," +
" name VARCHAR NOT NULL," +
" jid INTEGER NOT NULL," +
" hid INTEGER NOT NULL," +
" gid INTEGER NOT NULL," +
" quantity INTEGER NOT NULL," +
" CONSTRAINT Cracker_Primary PRIMARY KEY (cid)," +
" CONSTRAINT Cracker_Name_Unique UNIQUE(name)," +
" CONSTRAINT Joke_Foreign FOREIGN KEY (jid) REFERENCES Jokes(jid)," +
" CONSTRAINT Hat_Foreign FOREIGN KEY (hid) REFERENCES Hats(hid), " +
" CONSTRAINT Gift_Foreign FOREIGN KEY (gid) REFERENCES Gifts(gid)" +
")";
I am trying To Create Tables in mysql dynamically And Assign them Name Using The Email Address User Provided. But Whenever I try to Assign Table Name dynamically it shows me error and i don,t know anyother way to fulfil my requirement.
Here is The Code I Wrote
String TableName = Email.getText();
try {
String myTableName = "CREATE TABLE '" + TableName + "' "
+ "(id INTEGER not NULL, "
+ " first VARCHAR(255), "
+ " last VARCHAR(255), "
+ " age INTEGER, "
+ " PRIMARY KEY ( id ))";;
Class.forName(m.RegisterationString);
java.sql.Connection con;
con = DriverManager.getConnection(m.URL, m.UserName, m.Password);
Statement State = con.createStatement();
//This line has the issue
State.executeUpdate(myTableName);
System.out.println("Table Created");
}
In MySQL the name of table should not be between '' it can be between :
String myTableName ="CREATE TABLE `" + tableName + "`"
//--------------------------------^-----------------^
Note for good pratice don't start the name of variable with upper letter like State or TableName, Email
I have a java application that inserts records into the database from the textboxes. The problem is that when i click ADD it gives the following error:
com.microsoft.sqlserver.jdbc.SQLServerException: Violation of PRIMARY KEY constraint 'PK__customer__A1B71F90E76B7658'. Cannot insert duplicate key in object 'dbo.customer'. The duplicate key value is (5)
There is no duplication in my table and i cannot understand what to do. This is the first time i have encountred this error. No column in my database allows null and cust_id is a foreign key in another table. Here is my code
stmt = conn.createStatement();
String sql = "insert into customer (cust_id, cust_name, father_name, birth_date, CNIC, city, card_num, acc_num, bank_name, address, email, ph_num) values ( " + String.valueOf(txtcust_id1.getText()) + ",'" + txtcust_name1.getText()
+ "','" + txtf_name1.getText() + "','" + txtb_date1.getText() + "','" + txtcnic1.getText() + "','" + txtcity1.getText() + "','" + txtcard_num1.getText() + "','" + txtacc_num1.getText() + "','" + txtb_n1.getText() + "','" + txtadd1.getText() + "','" +
txtemail1.getText() + "','" + txtph_num1.getText() + "' )";
stmt.executeUpdate(sql);
System.out.println("Successful");
int rowsAffected = stmt.executeUpdate(sql);
String msg = "Insert Query Execution Failed";
if(rowsAffected > 0) {
JOptionPane.showMessageDialog(null, "Query Successful");
}
else {
JOptionPane.showMessageDialog(this, msg, "Execution Alert", JOptionPane.INFORMATION_MESSAGE);
}
i can't use parametric query because i can't seem to handle date and money in it.
Your code does:
stmt.executeUpdate(sql);
System.out.println("Successful");
int rowsAffected = stmt.executeUpdate(sql);
So it executes the same SQL, containing a hard-coded primary key, twice. That's why you get this exception.
BTW, your code is extremely fragile (just try adding an apostrophe in one of the strings you're inserting) , and a good candidate for a SQL injection attack. Learn about prepared statements.
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