I would like to insert data into the MySQL database that I am using.I get this ERROR.This is my code:
public boolean insertValues(String gisuniqkey,String objtype,String objkey,String lat,String lng)
{
int rc=-1;
try {
if(conn==null)
{
System.out.println("The connection was not initialized.");
return false;
}
Statement st=(Statement) conn.createStatement();
//lots of String concatenation,very expensive...BAD...use StringBuilder instead
String sql="Insert into ZMAPERP_GIS_DB (GISUNIQKEY,OBJTYPE,OBJKEY,LATITUDE,LONGITUDE) values("+gisuniqkey+","+objtype+","+objkey+","+lat+","+lng+");";
System.out.println(sql);
rc=st.executeUpdate(sql);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return rc>0?true:false;
}
I think the insert statement should be like this, Use single quotes around the values:
"Insert into ZMAPERP_GIS_DB (GISUNIQKEY,OBJTYPE,OBJKEY,LATITUDE,LONGITUDE) values('"+gisuniqkey+"','"+objtype+"','"+objkey+"','"+lat+"','"+lng+"');";
Edit
Try it yourself in a command. What will work:
Option 1:
INSERT INTO ZMAPERP_GIS_DB (GISUNIQKEY,OBJTYPE,OBJKEY,LATITUDE,LONGITUDE)
VALUES(asdasd,asdasd,asdasd,asdasd);
Option 2:
INSERT INTO ZMAPERP_GIS_DB (GISUNIQKEY,OBJTYPE,OBJKEY,LATITUDE,LONGITUDE)
VALUES('asdasd','asdasd','asdasd','asdasd');
I would think that option 2 will work
Edit 2
But as mention in the comment. Using the prepare statement is recommended. Because this is open for sql injections
Reference:
SQL injection
JDBC PreparedStatement Example – Insert A Record
You should use PreparedStatements to avoid problems with building query strings.
PreparedStatement statement = null;
String insertSql = "Insert into ZMAPERP_GIS_DB (GISUNIQKEY,OBJTYPE,OBJKEY,LATITUDE,LONGITUDE) values (?,?,?,?,?)";
conn.setAutoCommit(false);
statement = conn.prepareStatement(insertSql);
statement.setString(1, gisuniqkey);
statement.setString(2, objtype);
statement.setString(3, objkey);
statement.setString(4, lat);
statement.setString(5, lng);
con.commit();
String sql="Insert into ZMAPERP_GIS_DB (GISUNIQKEY,OBJTYPE,OBJKEY,LATITUDE,LONGITUDE) values('"+gisuniqkey+"','"+objtype+"','"+objkey+"','"+lat+"','"+lng+"');";
Although, I would suggest you inject variable values using prepared statement.
Related
I get an sql error when trying to insert something into my DB.
I give a bunch of input to my method, convert that input into strings or sql time and want to store it.
public static void setCourseList(String courseDescription, String courseName, LocalTime courseStart, LocalTime courseEnd, LocalDate courseDate, DayOfWeek courseDay) {
Connection conn = null;
try {
// db parameters
// path to db relative to run time directory
String url = "jdbc:sqlite:Holiday.db";
String sqlInsertCourse = "INSERT INTO COURSE (Name,Start,End,Date,Day,Description) VALUES (?, ?,?, ?,?, ?,);";
conn = DriverManager.getConnection(url);
System.out.println("Connected");
Statement stmt = conn.createStatement();
PreparedStatement pstmt = conn.prepareStatement(sqlInsertCourse);
pstmt.setString(1, courseName);
String courseStartString = courseStart.toString();
pstmt.setString(2, courseStartString);
java.sql.Time courseEndTime = Time.valueOf(courseEnd);
pstmt.setTime(3, courseEndTime);
java.sql.Date courseDateDate = java.sql.Date.valueOf(courseDate);
pstmt.setDate(4, courseDateDate);
String courseDayString = courseDay.toString();
pstmt.setString(5, courseDayString);
pstmt.executeUpdate();
pstmt.close();
System.out.println("Connection to SQLite has been established.");
// create tables if they do not exists
stmt.execute(sqlInsertCourse);
} catch (SQLException e) {
System.out.println(e.getMessage());
} finally {
try {
if (conn != null) {
conn.close();
}
} catch (SQLException ex) {
System.out.println(ex.getMessage());
}
}
}
I would expect it to store the input in my db.
I do get an [SQLITE_ERROR] SQL error or missing database (near ")": syntax error) error instead.
Any help is appreciated.
I am new to sql.
Change
String sqlInsertCourse = "INSERT INTO COURSE (Name,Start,End,Date,Day,Description) VALUES (?, ?,?, ?,?, ?,);";
To
String sqlInsertCourse = "INSERT INTO COURSE (Name,Start,End,Date,Day,Description) VALUES (?, ?,?, ?,?, ?);"; //<<<<<<<<<< extra comma removed
As per the comment on the line the final comma after the last ? has been removed.
Same as what Mike has answered, you can change it to
String sqlInsertCourse = "INSERT INTO COURSE (Name,Start,End,Date,Day,Description) VALUES (""put values here"");";
If you are wondering why it doesn't throw you an error, it's because there is no syntax error in the java, there's an error in the SQL which only the database can throw, but you're computer can't recognize. Hope this answers your question.
I don't have much experience in using JAVA with SQL Server or any other database, so I'm having some trouble at the moment.
I have the following code:
public void insertProjeto(Planejado p){
String verifica="SELECT cd_projeto FROM PROJETO WHERE cd_projeto = ?";
String sqlInsert="INSERT INTO PROJETO (cd_projeto, ds_projeto) VALUES (?, ?)";
String projeto = p.getProjeto();
String nomeProjeto = p.getNomeProj();
PreparedStatement stmt;
try {
stmt = getDBConnection().prepareStatement(verifica);
stmt.setString(1, projeto);
ResultSet rs = stmt.executeQuery();
if (rs.equals("") || rs.equals(null)) {
System.out.println("------------------");
stmt = getDBConnection().prepareStatement(sqlInsert);
stmt.setString(1, projeto);
stmt.setString(2, nomeProjeto);
stmt.executeUpdate();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
My goal is insert a register without duplicates, but for some reason my "if" isn't working.
Can anybody help me find out why?
Thanks in advance
When obtaining a ResultSet, you must call its next() method to have it progress to the first row of data if any. In case there is no data in the ResultSet object, rs.next() will return false.
There are better ways to prevent duplicates on SQL tables depends on what SQL server you're using (MS SQL, MySQL etc.)
If you're using MySQL, you can make cd_projeto a primary key and call REPLACE INTO instead of INSERT INTO, it will result in updating the record for cases it exist and inserting a new one when it doesn't.
Solved.
try {
stmt = getDBConnection().prepareStatement(verifica);
stmt.setString(1, projeto);
ResultSet rs = stmt.executeQuery();
while(!rs.next()) {
System.out.println("------------------");
stmt = getDBConnection().prepareStatement(sqlInsert);
stmt.setString(1, projeto);
stmt.setString(2, nomeProjeto);
stmt.executeUpdate();
break;
}
} catch (SQLException e) {
e.printStackTrace();
}
Don't know if it's the best way to do it, but works.
Thank you for the tips
package controller;
import pojo.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class JdbcConn {
int found=0;
public boolean register(Member c)
{
Connection conn=null;
Statement stmt =null;
ResultSet rs = null;
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
conn= DriverManager.getConnection("jdbc:oracle:thin:#localhost","system","system");
stmt=conn.createStatement();
System.out.println("Data base is connected");
rs= stmt.executeQuery("select USERID from member");
System.out.println("Hi");
while(rs.next())
{
System.out.println("bye");
if((c.getUserId()).equals(rs.getString(1)) )
{
System.out.println("bye");
found=1;
break;
}
}
if(found==1)
{
return false;
}
else
stmt.executeUpdate("insert into member values ('"+ c.getName() +"','"+c.getEmail()+ "','"+c.getMobileNo()+ "','"+c.getAddress1()+"',,'"+c.getAddress2()+"','"+c.getUserId()+"','"+c.getPassword()+"','"+c.getSecretQuestion()+"','"+c.getSecretAnswer()+"')");
return true;
}
catch(ClassNotFoundException e)
{
System.out.print(e);
e.printStackTrace();
}
catch(SQLException e)
{
System.out.print(e);
}
return false;
}
public boolean login(String userid, String password)
{
Connection conn=null;
Statement stmt =null;
ResultSet rs = null;
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
conn = DriverManager.getConnection("jdbc:oracle:thin:#localhost","system","system");
stmt=conn.createStatement();
rs= stmt.executeQuery("select userid, password from member where userid = '"+userid+"'");
if(rs==null)
{
return false;
}
else
{
while(rs.next())
{
String uid,pass;
uid=rs.getString(1);
pass=rs.getString(2);
if(password.equals(pass))
{
return true;
}
else
{
return false;
}
}
}
}
catch(ClassNotFoundException e)
{
System.out.print(e);
}
catch(SQLException e)
{
System.out.print(e);
}
return false;
}
}
I am invoking the code from one servlet. It is showing me the following output.Though the same code is working correctly in somewhere else:
Output:
Data base is connected
Hi
java.sql.SQLException: ORA-00936: missing expression
Can anyone help me with the problem.
In your insert you have the following
+c.getAddress1()+"',,'"+c.getAddress2()+
There should be only one comma instead of two
I suggest to use PreparedStatement to avoid such error.
Advantage of using PreparedStatement over Statement
A SQL statement is precompiled and stored in a PreparedStatement object.
This object can then be used to efficiently execute this statement multiple times.
Reduces execution time.
Automatic prevention of SQL injection attacks by builtin escaping of quotes and other special characters
Read more PreparedStatements and performance
See Java Tutorial on Using Prepared Statements
sample code:
String insertTableSQL = "INSERT INTO DBUSER"
+ "(USER_ID, USERNAME, CREATED_BY, CREATED_DATE) VALUES"
+ "(?,?,?,?)";
PreparedStatement preparedStatement = dbConnection.prepareStatement(insertTableSQL);
preparedStatement.setInt(1, 11);
preparedStatement.setString(2, "mkyong");
preparedStatement.setString(3, "system");
preparedStatement.setTimestamp(4, getCurrentTimeStamp());
// execute insert SQL stetement
preparedStatement .executeUpdate();
Find complete Sample example here to learn more about it.
Use prepared statements to avoid such issues. This will also avoid issues which you may face because of certain special characters like single quotes etc.
If not, then try one of the following:
If there is no column between address1 and address2, then use below (extra comma removed):
String query = " stmt.executeUpdate("insert into member values ('"+ c.getName() +"','"+c.getEmail()+ "','"+c.getMobileNo()+ "','"+c.getAddress1()+"','"+c.getAddress2()+"','"+c.getUserId()+"','"+c.getPassword()+"','"+c.getSecretQuestion()+"','"+c.getSecretAnswer()+"')"); ";
stmt.executeUpdate (query);
If there is supposed to be an empty value that has to be inserted, then use below (an empty field is inserted using ,'', )
String query = " stmt.executeUpdate("insert into member values ('"+ c.getName() +"','"+c.getEmail()+ "','"+c.getMobileNo()+ "','"+c.getAddress1()+"', '' ,'"+c.getAddress2()+"','"+c.getUserId()+"','"+c.getPassword()+"','"+c.getSecretQuestion()+"','"+c.getSecretAnswer()+"')"); ";
stmt.executeUpdate (query);
In your insert statement you can specify which columns you insert/update that would correspond to the SQL syntax having insert into member (col1, col2) values (val1, val2). The number of columns should be exactly the same before and after values in parenthesis. Incorrect number of columns or values are caused the error.
Hi I've been trying to insert a string into a sqlite database through java. but the string parameter I'm passing in the values sql statement has quotation marks in it as content. I'm thinking that is the error I'm getting why it isn't inserting into the database. is there a way to bypass the quotation marks in the insert statement. thank you.
this is the code:
public void addNote(String topicadd, String contentadd) throws Exception
{
try
{
getConnection();
statement = conn.createStatement();
statement.executeUpdate("insert into tbl_notes (notes_topic, notes_content) values ('" + topicadd + "', '" + contentadd +"')");
System.out.println("inserted note");
}
catch (Exception m)
{`enter code here`
System.out.println("error insert topic");
System.out.println(m.getMessage());
}
}
this is the parameter kind of long... this is all in contentadd
import java.sql.*;
Resultset rset = null; (this has no new ResultSet() initialization)
Connection conn = null; (this has no new initialization too...)
Statement statement = null; (this has now new initialization)
always.....
try
{
}
catch (Exception e) <- can switch e for any other alphabet
{
e.getMessage();
System.out.println("error this module"); <- personal practice
throw e;
}
- getting connection
Class.forName("org.sqlite.JDBC");
conn = DriverManager.getConnection("jdbc:sqlite:m.db");
*** this is sqlite connection format 'm.db' is the database name
establish connection first..
statement syntax follows:
statement = conn.createStatement();
rset = statement.executeQuery("select * from tbl_notes");
- executeQuery is used for SELECT sql statements
rset = statement.executeUpdate("insert into tbl_notes (ID, status) values
('100', 'status here');
the whole text is in string contentadd, I'm making a short note-taking program... Well, it doesn't execute the insert statement... error somewhere near (word from text) on command prompt... I'm using sqlite... Please let me know if you need more detail. thank you again.
Use a PreparedStatement to insert values containing special characters:
getConnection();
PreparedStatement statement = conn.prepareStatement("insert into tbl_notes (notes_topic, notes_content) values (?, ?)");
statement.setString(1, topicadd);
statement.setString(2, contentadd);
statement.executeUpdate();
As you see you can use parameters with a PreparedStatement which can contain also quotation marks.
Also you get some protection against SQL injection because the Strings given to a PreparedStatement are escaped accordingly.
need help please..
Connection cn = DriverManager.getConnection ("jdbc:mysql://localhost/posdb", "root", "");
PreparedStatement dat = cn.prepareStatement("INSERT INTO order VALUES('"+num+"',"+buyamount.elementAt(0)+","+buyamount.elementAt(1)+","+buyamount.elementAt(2)+","+buyamount.elementAt(3)+","+buyamount.elementAt(4)+","+buyamount.elementAt(5)+","+buyamount.elementAt(6)+","+buyamount.elementAt(7)+","+buyamount.elementAt(8)+","+buyamount.elementAt(9)+","+buyamount.elementAt(10)+","+buyamount.elementAt(11)+","+buyamount.elementAt(12)+","+buyamount.elementAt(13)+","+buyamount.elementAt(14)+","+buyamount.elementAt(15)+","+buyamount.elementAt(16)+","+buyamount.elementAt(17)+","+buyamount.elementAt(18)+","+buyamount.elementAt(19)+","+tot+","+tot2+","+(tot2-tot)+")");
System.out.println(dat);
dat.executeUpdate();
cn.close();
Error message :
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 'order VALUES('20130605093640',1, 0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,9500,1200' at line 1
num is a string, tot and tot2 are integers, and buyamount is a vector of integer.
thanks.. any help will be appreciated..
Order is a reserved word in MySQL -- use backticks around it:
INSERT INTO `order`...
http://dev.mysql.com/doc/refman/5.5/en/reserved-words.html
In addition you might want to consider using a prepared statement the proper way. This will help avoid sql injection and make your code easier to read.
private static final String INSERT = "insert into myTable values(?,?,?)";
public void insertData(String varA, int numB, Date myDate) throws SQLException {
Connection cn=null;
PreparedStatement ps=null;
try {
cn = DriverManager.getConnection("...your connection string...");
ps = cn.prepareStatement(INSERT);
ps.setString(1, varA);
ps.setInt(2, numB);
ps.setDate(3, myDate);
ps.executeUpdate();
}catch(SQLException sqe) {
throw sqe;
} finally {
try {ps.close();}catch(Exception ex) {}
try {cn.close();}catch(Exception ex) {}
}
}