I've got this error from my jdbc driver. I don't know why, tho.
Here's the corresponding code:
try {
String colNames = " ";
for (int i=0; i<cols.size(); i++) {
if (i == cols.size()-1) {
colNames += cols.get(i);
} else if (i<cols.size()) {
colNames += cols.get(i)+", ";
}
}
String colValues = " ";
for (int i=0; i<values.size(); i++) {
if (i == values.size()-1) {
colValues += values.get(i);
} else if (i<values.size()) {
colValues += values.get(i) + ", ";
}
}
System.out.println(
"INSERT INTO `" + tableName + "` (" + colNames + ") VALUES (" + colValues + ") "
);
//System.out.println(kerdojel);
PreparedStatement pst = connHandler.conn.prepareStatement
("INSERT INTO `" + tableName + "` (" + colNames + ") VALUES (" + colValues + ") ");
pst.executeUpdate();
pst.close();
}
"values" and "cols" are ArrayLists that contains the data from the JTable.
cols are the Column names and values are the cell values.
The output for the Sysout:
INSERT INTO `TableOne` ( nev, kor, lakhely) VALUES ( asd, 1, asd)
The error:
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown column 'asd' in 'field list'
That is not how the PreaparedStatement was intended to be used. When you use a PreparedStatement, you can specify the values by using one of the "set" methods.
Here is an example:
String colNames = " ";
String colValues = " ";
for (int i=0; i<cols.size(); i++) {
if(i!=0){
colNames += ", ";
colValues += ", ";
}
colNames += cols.get(i);
colValues += "?";
}
try (PreparedStatement pst = connHandler.conn.prepareStatement("INSERT INTO `" + tableName + "` (" + colNames + ") VALUES (" + colValues + ") ");){
for (int i = 0; i < values.size(); i++) {
pst.setString(i+1,values.get(i));
}
pst.executeUpdate();
}
You should use the appropriate "set" method based on the column's data type (setInt(...), setDate(...), etc.). You can find more details here
Try to use command like these one to check problem existed.
PREPARE mycmd FROM 'INSERT INTO TableOne(nev,kor) VALUES (?, ?)'
Related
I am trying to Create a table Model (i, y1, y2 .... yd) in Vertica using JAVA. Column i is integer and all others are REAL. I used the following code to create it. However it is showing syntax error at or near null. Does anybody know what that means? The connection works for the program.
public void createMODEL(int d)
{
int x;
try
{
Statement stmt = conn.createStatement();
String createquery = "CREATE TABLE MODEL ( "
+ "i integer primary key ";
for (x=1;x<=d;x++) createquery+= " , " + Y[x] + " REAL ";
createquery += ")";
stmt.executeUpdate(createquery);
}
catch (Exception e)
{
System.out.println("Error while executing create model query");
System.out.print(e);
System.exit(0);
}
}
Y is defined as follows -
String Y[]=new String[100];
I guess you should check if Y[x] is not null:
Statement stmt = conn.createStatement();
String createquery = "CREATE TABLE MODEL ( "
+ "i integer primary key ";
for (x=1;x<=d;x++) {
if (Y[x] != null) createquery+= " , " + Y[x] + " REAL ";
}
createquery += ")";
stmt.executeUpdate(createquery);
This works for me for MySQL. Try this.
String Y[] = new String[100];
Y[0] = "h";
Y[1] = "ha";
Y[2] = "hat";
Y[3] = "hati";
Y[4] = "hatim";
System.out.println("Your columns array : " + Arrays.deepToString(Y));
String createquery = "CREATE TABLE MODEL ( " + "i integer primary key ";
for (int i = 0; i < Y.length; i++) {
if (Y[i] != null)
createquery += " , " + Y[i] + " REAL ";
}
createquery += ");";
System.out.println("Your create query : " + createquery);
I have written a java code which will fetch the data from the table and show the output. This is basically a script that I want to run through Nashorn.
Below is the code I'm trying
public static void main(String args[]) throws ScriptException{
ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn");
String script3 = "count = 0; "
+ "keyList = new java.util.ArrayList; "
+ "valueList = new java.util.ArrayList;"
+ "keyList.add('username'); "
+ "keyList.add('password'); "
+ "valueList.add('admin'); "
+ "valueList.add('admin');"
+ "java.lang.System.out.println('keyList :: ' + keyList); "
+ "java.lang.System.out.println('KeyValue :: ' + valueList);"
+ "sql = \" select * from credentials where 'isActive'='1'\";"
+ "java.lang.System.out.println('keyList.size() :: ' + keyList.size());"
+ "for (i = 0; i < keyList.size(); i++){"
+ " sql += and \\' + keyList.get(i) + \\' = \\' + valueList.get(i) + \\';}"
+ "java.lang.System.out.println('Search SQL : ' + sql); "
+ "con = GetConnected.connectToDatabase('my_db');"
+ "ps = con.prepareStatement(sql); "
+ "ps.setString(1, \"1\");"
+ "rs = ps.executeQuery(); "
+ "if (rs.isBeforeFirst()) {"
+ " count=1; "
+ " java.lang.System.out.println('Data is present in database'); "
+ "}"
+ "else "
+ " java.lang.System.out.println('Data is not present in database'); "
+ " rs.close(); " + " st.close(); " + " con.close(); ";
engine.eval(script3);
}
The error I'm getting is
Exception in thread "main" javax.script.ScriptException: <eval>:1:904 Missing close quote
count = 0; keyList = new java.util.ArrayList; valueList = new java.util.ArrayList;keyList.add('username'); keyList.add('password'); valueList.add('admin'); valueList.add('admin');java.lang.System.out.println('keyList :: ' + keyList); java.lang.System.out.println('KeyValue :: ' + valueList);sql = " select * from credentials where 'isActive'='1'";java.lang.System.out.println('keyList.size() :: ' + keyList.size());for (i = 0; i < keyList.size(); i++){ sql += and \' + keyList.get(i) + \' = \' + valueList.get(i) + \';}java.lang.System.out.println('Search SQL : ' + sql); con = GetConnected.connectToDatabase('my_db');ps = con.prepareStatement(sql); ps.setString(1, "1");rs = ps.executeQuery(); if (rs.isBeforeFirst()) { count=1; java.lang.System.out.println('Data is present in database'); }else java.lang.System.out.println('Data is not present in database'); rs.close(); st.close(); con.close();
^ in <eval> at line number 1 at column number 904
at jdk.nashorn.api.scripting.NashornScriptEngine.throwAsScriptException(NashornScriptEngine.java:467)
at jdk.nashorn.api.scripting.NashornScriptEngine.compileImpl(NashornScriptEngine.java:534)
at jdk.nashorn.api.scripting.NashornScriptEngine.compileImpl(NashornScriptEngine.java:521)
at jdk.nashorn.api.scripting.NashornScriptEngine.evalImpl(NashornScriptEngine.java:399)
at jdk.nashorn.api.scripting.NashornScriptEngine.eval(NashornScriptEngine.java:155)
at javax.script.AbstractScriptEngine.eval(AbstractScriptEngine.java:264)
at com.engine.nashorn.Test.main(Test.java:87)
Caused by: jdk.nashorn.internal.runtime.ParserException: <eval>:1:904 Missing close quote
count = 0; keyList = new java.util.ArrayList; valueList = new java.util.ArrayList;keyList.add('username'); keyList.add('password'); valueList.add('admin'); valueList.add('admin');java.lang.System.out.println('keyList :: ' + keyList); java.lang.System.out.println('KeyValue :: ' + valueList);sql = " select * from credentials where 'isActive'='1'";java.lang.System.out.println('keyList.size() :: ' + keyList.size());for (i = 0; i < keyList.size(); i++){ sql += and \' + keyList.get(i) + \' = \' + valueList.get(i) + \';}java.lang.System.out.println('Search SQL : ' + sql); con = GetConnected.connectToDatabase('my_db');ps = con.prepareStatement(sql); ps.setString(1, "1");rs = ps.executeQuery(); if (rs.isBeforeFirst()) { count=1; java.lang.System.out.println('Data is present in database'); }else java.lang.System.out.println('Data is not present in database'); rs.close(); st.close(); con.close();
^
at jdk.nashorn.internal.parser.Lexer.error(Lexer.java:1706)
at jdk.nashorn.internal.parser.Lexer.scanString(Lexer.java:988)
at jdk.nashorn.internal.parser.Lexer.lexify(Lexer.java:1615)
at jdk.nashorn.internal.parser.AbstractParser.getToken(AbstractParser.java:132)
at jdk.nashorn.internal.parser.AbstractParser.nextToken(AbstractParser.java:211)
at jdk.nashorn.internal.parser.AbstractParser.nextOrEOL(AbstractParser.java:170)
at jdk.nashorn.internal.parser.AbstractParser.next(AbstractParser.java:157)
at jdk.nashorn.internal.parser.Parser.parse(Parser.java:281)
at jdk.nashorn.internal.parser.Parser.parse(Parser.java:249)
at jdk.nashorn.internal.runtime.Context.compile(Context.java:1286)
at jdk.nashorn.internal.runtime.Context.compileScript(Context.java:1253)
at jdk.nashorn.internal.runtime.Context.compileScript(Context.java:625)
at jdk.nashorn.api.scripting.NashornScriptEngine.compileImpl(NashornScriptEngine.java:532)
... 5 more
I think the place where the keyList and valueList value added to sql query it is giving problem.
sql += and \\' + keyList.get(i) + \\' = \\' + valueList.get(i) + \\';}"
that + will keep on adding until end of the script.
I am trying to create an insertion in some tables with random data but i have a problem with the duplicates.
I wrote an insertion of random records in postgresql b but it returns duplicates detection and there should be no duplicates i am using every name for exactly 2680 times and the names are 22 for 58960 records total of table play_in please check and tell what's wrong with it and how does produce a duplicate.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
import java.util.Random;
public class PostgreSQLJDBC {
public static void main(String args[]) {
Connection c = null;
Statement stmt = null;
int year;
int year1;
int num_rating;
int num_ratingAvg;
String[] round = new String[5];
round[0] = "32nd";
round[1] = "16th";
round[2] = "quarter_final";
round[3] = "SemiFinal";
round[4] = "FInal";
String[] name1 = new String[22];
name1[0] = "ahmed";
name1[1] = "mohamed";
name1[2] = "mai";
name1[3] = "salma";
name1[4] = "walid";
name1[5] = "wael";
name1[6] = "fadwa";
name1[7] = "nada";
name1[8] = "nahla";
name1[9] = "mustafa";
name1[10] = "ola";
name1[11] = "omar";
name1[12] = "amr";
name1[13] = "beshoy";
name1[14] = "marina";
name1[15] = "gerges";
name1[16] = "botros";
name1[17] = "mina";
name1[18] = "menna";
name1[19] = "feasal";
name1[20] = "youssef";
name1[21] = "moussa";
Random id = new Random();
Random roundc = new Random();
String round1;
int idc;
String name;
Random namec = new Random();
int namecounter = 0;
Random belle = new Random();
int belec = 0;
Random yearc = new Random();
Random num_ratingsc = new Random();
int num_ratingSum = 0;
// roundc.nextInt(4);
try {
Class.forName("org.postgresql.Driver");
c = DriverManager.getConnection(
"jdbc:postgresql://localhost:5432/a2", "mohamed", "1234");
System.out.println("Opened database successfully");
String sql3;
String sql4;
stmt = c.createStatement();
String sql = "CREATE TABLE cup_matches "
+ "(MID INT PRIMARY KEY NOT NULL,"
+ " ROUND TEXT NOT NULL, "
+ " YEAR INT NOT NULL, "
+ " NUM_RATINGS INT NOT NULL, "
+ " RATING INT NOT NULL)";
String sql1 = "CREATE TABLE played_in "
+ "(MID INT NOT NULL,"
+ " NAME TEXT NOT NULL, "
+ " YEAR INT NOT NULL, "
+ " POSITION INT NOT NULL, "
+ "CONSTRAINT pk_played_in PRIMARY KEY (MID, NAME));";
String sql2 = "ALTER TABLE played_in ADD CONSTRAINT ref FOREIGN KEY (MID) REFERENCES cup_matches (MID);";
stmt.executeUpdate(sql);
stmt.executeUpdate(sql1);
stmt.executeUpdate(sql2);
for (int i = 0; i < 2680; i++) {
year = yearc.nextInt(2014 - 1900) + 1900;
num_rating = num_ratingsc.nextInt(1000);
num_ratingSum += num_rating;
num_ratingAvg = num_ratingSum / (i + 1);
round1 = "\'" + round[roundc.nextInt(4)] + "\'";
sql3 = "INSERT INTO cup_matches (MID, ROUND, YEAR, NUM_RATINGS, RATING) "
+ "VALUES ("
+ i
+ ", "
+ round1
+ ", "
+ year
+ ", "
+ num_rating + ", " + num_ratingAvg + ");";
stmt.executeUpdate(sql3);
System.out.println(sql3);
}
for (int j = 0; j < 58960; j++) {
idc = j;
idc = (idc >= 2679) ? 0 : idc;
year1 = yearc.nextInt(2014 - 1900) + 1900;
num_rating = num_ratingsc.nextInt(1000);
if ((belle.nextInt(2 - 1) + 1) == 1 && belec < 118) {
name = "\'" + name1[namecounter] + "belle" + "\'";
sql4 = "INSERT INTO played_in (MID, NAME, YEAR, POSITION) "
+ "VALUES (" + idc + ", " + name + ", " + year1
+ ", " + num_rating + ");";
stmt.executeUpdate(sql4);
belec++;
idc++;
System.out.println(idc + " " + namecounter);
namecounter++;
} else {
name = "\'" + name1[namecounter] + "\'";
sql4 = "INSERT INTO played_in (MID, NAME, YEAR, POSITION) "
+ "VALUES (" + idc + ", " + name + ", " + year1
+ ", " + num_rating + ");";
stmt.executeUpdate(sql4);
namecounter++;
idc++;
System.out.println(idc + " " + namecounter);
}
namecounter = (namecounter < 22) ? namecounter : 0;
}
// stmt.executeUpdate(sql);
// stmt.executeUpdate();
// stmt.executeUpdate(sql2);
stmt.close();
c.close();
} catch (Exception e) {
System.err.println(e.getClass().getName() + ": " + e.getMessage());
System.exit(0);
}
System.out.println("Table created successfully");
}
}
This line:
idc = (idc >= 2679) ? 0 : idc;
is causing you problems as you later use idc as the value for mid, which is your primary key. This line returns 0 when idc is >= 2679, which will give you duplicate key errors.
This line makes idc = 0 for each j value above 2679.
idc = j;
idc = (idc >= 2679) ? 0 : idc;
The first time, it will insert in the table played_in with idc = 0 and will insert that value for each name, when the name counter starts again with 0:
namecounter = (namecounter < 22) ? namecounter : 0;
It will try to insert the first name with 0 again and it will fail due to duplicate key error
I'm wanting to insert an entry if it does not exist otherwise update the entry, I couldn't use the ON DUPLICATE KEY UPDATE, I got confused with the syntax. So I tried to do something like this:
final String QUERY = "REPLACE INTO skills SET VALUES (" + insert(player) + ") WHERE playername = '" + player.getUsername() + "'";
statement.execute(QUERY);
statement.close();
connection.close();
}
private static String insert(Player player) {
String stringToReturn = "'" + player.getUsername() + "',";
for (int index = 0; index < 25; index++) {
stringToReturn += player.getSkills().getLevels()[index] + "," + ((int) player.getSkills().getXp()[index]) + ",";
}
stringToReturn = stringToReturn.substring(0, stringToReturn.length() - 1);
return stringToReturn;
}
But that's incorrect syntax so I was wondering how I could do this?
playername is primary key
I think the correct syntax to make ON DUPLICATE KEY UPDATE work for you is:
"INSERT INTO skills (playerName, otherColumn)
VALUES ('" + player.getUsername() + "', '" + insert(player) +"')
ON DUPLICATE KEY UPDATE otherColumn = VALUES(otherColumn)";
I have 80000 recodes that are need to insert into database especially in table: temp(ts, temp)
temp is INT.
The problem is almost 20000 recodes are null, so I am wondering how to insert NULL into DB when dataType is INT.
I tried this:
String val = null;
//insert(ts, val) into temp
String sql = "INSERT INTO temp" + "(val)" + " VALUES" + "('" + val + "')";
Statement st = (Statement) conn.createStatement();
count = st.executeUpdate(sql);
unfortunately insert is failure. Print out the exception message:
Incorrect integer value: 'null' for column 'val' at row 1"
Wish someone can help me with it. Thank you.
You should use a PreparedStatement and use setNull(int, int):
String sql = "INSERT INTO temp(val) VALUES (?)";
PreparedStatement st = con.prepareStatement(sql);
if (/* int value is not null */) {
st.setInt(1, value);
} else {
set.setNull(1, Types.INTEGER);
}
count = st.executeUpdate();
As an alternative to Mark Rotteveel's answer, you can also use PreparedStatement.setObject(int, Object, int).
You specify the SQL Type (3rd Parameter), and if the object is null, it inserts a null automatically. It's faster and easier.
String sql = "INSERT INTO temp(val) VALUES (?)";
PreparedStatement st = con.prepareStatement(sql);
st.setObject(1, value, Types.INTEGER);
count = st.executeUpdate();
You should consider using prepared statements. If you do, you'll find information on how to deal with nulls here and elsewhere.
If you're 100% sure your val value is clean and won't cause SQL Injection (rare, but possible), then the "built string" approach needs to explicitly use null when defining the value:
String sql = "INSERT INTO temp (val) VALUES (";
if (val == null) {
sql += "null";
} else {
sql += val;
}
sql += ")";
I have solved this problem.
The codes update as following:
String sql= null;
if(val.isEmpty()){
System.out.println(val);
System.out.println("Insert ts: " + ts + " val: null");
sql= "INSERT INTO " + table + "(ts,val,pointId)" + " VALUES" + "(" + "'" + ts + "'" + ", " + "NULL" + " , " + "'" + pointId + "'" + ")";
}
else{
System.out.println("Insert ts: " + ts + " val: " + val);
sql= "INSERT INTO " + table + "(ts,val,pointId)" + " VALUES" + "(" + "'" + ts + "'" + ", " + "'" + val + "'" + ", " + "'" + pointId + "'" + ")";
}
Statement st = (Statement) conn.createStatement(); //create the instances of statement
count = st.executeUpdate(sql);
Basically, if insert null into database, just do insert into table(val) value(NULL).
You should explicitly CAST the NULL as an INT
...VALUES(...CAST(NULL AS INT)
It sounds like your are sending "null" in when you should be sending an int. Perhaps try something like
(val == null ? "" : val)