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) {}
}
}
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.
Recently I'm just learning some HTML, JSP and servlets for a university project, the thing is that I made a database into MySQL Workbench with id primary key, auto increment , then some fields like username, password, firstname, lastname, and so on.
The goal is to make a login page and register page, for some reason if I push data with MySQL Workbench into the database it will let me retrieve it with my login form and my select statment, but for some reason I'm doing the same thing with register but in this case with the query INSERT.
So, after research, I did preparestatment and changed the executeQuery to executeUpdate and everything, but my log says a nullPointerException somewhere, I know it may be a simple and silly error that I'm not seeing, but I'm new at this. This is what U have made so far to insert data into my database:
public static UserBean registarUsuario(UserBean bean){
//preparing some objects for connection
Statement stmt = null;
ResultSet rs = null;
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException ex) {
System.out.println("Error al cargar el driver");
System.out.println(ex.getMessage());
}
String firstname = bean.getFirstName();
String lastname = bean.getLastName();
String username = bean.getUsername();
String password = bean.getPassword();
boolean admin = bean.isAdmin();
int tipo = bean.getType();
String insertQuery =
"insert into idusuario (firstname,lastname,username,password,admin,tipo) values ('"+firstname+"','"+lastname+"','"+username+"','"+password+"','"+admin+"','"+tipo+"')";
System.out.println("Firstname is " + firstname);
System.out.println("Surname is " + lastname);
System.out.println("Query: "+insertQuery);
try
{
//connect to DB
currentCon = DriverManager.getConnection("jdbc:mysql://localhost:3306/usuarios", "root", "admin");
rs = stmt.executeQuery(insertQuery);
...
My output:
Info: Query: insert into idusuario
(firstname,lastname,username,password,admin,tipo) values
('jhon','marston','jmar','123','true','0') Info: Error :
java.lang.NullPointerException
The thing is that Netbeans doesn't even tell me where the NPE is happening so I'm kind of confused, I don't know if the query is wrong or if something else is, because as I can see in my output, the query seems ok.
I leave you here my database structure
You are assigining the stmt as null and never initializing it.
Statement stmt = null;
ResultSet rs = null;
Then you are trying to use it:
rs = stmt.executeQuery(insertQuery);
You will need to do something like this before you use it:
PreparedStatement stmt=currentCon.prepareStatement(yourQuery);
So, after research, i did preparestatment and changed the executeQuery
to executeUpdate and everything, but my log says a
nullPointerException somewhere, i know it may be a simple and silly
error that im not seeing, but understand that im new at this. this is
what i have made so far to insert data into my database
When we use insert,update or delete we need to use executeUpdate.
When we use select we need to use executeQuery.
In your example you are doing executeQuery for an insert. This is wrong. You need to use this:
rs = stmt.executeUpdate(insertQuery);
You're getting a NPE because you are trying to retrieve the results where there are none.
Here is a nice thing to do to help you reduce boilerplate code... (so you don't have to keep repeating yourself with db initialization values)
Create a class for your database connection:
public class DBConnection {
private static String url = null;
private static Connection conn = null;
public static Connection getConnection(){
try{
Class.forName("com.mysql.jdbc.Driver");
url = "jdbc:mysql://localhost:3306/usuarios";
conn = DriverManager.getConnection(url,"root","admin");
} catch (Exception e) {
System.out.println(e);
}
return conn;
}
}
Now you can use this in all your other classes like this:
public static UserBean registarUsuario(UserBean bean){
try(Connection conn= DBConnection.getConnection()){
PreparedStatement pst = conn.prepareStatement("insert into idusuario (firstname,lastname,username,password,admin,tipo) values (?,?,?,?,?,?);");
pst.setString(1, bean.getFirstName());
pst.setString(2, bean.getLastName());
pst.setString(3, bean.getUserName());
pst.setString(4, bean.getPassword());
pst.setBoolean(5, bean.isAdmin());
pst.setInt(6, bean.getType());
pst.executeUpdate();
}catch (SQLException e) {
e.printStackTrace();
}
}
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con1=DriverManager.getConnection("jdbc:odbc:MyDatabase");
st1=con1.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY);
System.out.println("Connect database in BallMoves1.java .......");
/*the below line giving error*/
rs1 = st1.executeQuery("insert into highscore" + " (score) " + "values('"+score+"')");
System.out.println("Score is inserted..");
System.out.println("Score......."+score);
}catch(Exception e){ e.printStackTrace();}
/*highscore is table and attributes of table are (sid,score).
the resulting error is:
Connect database in BallMoves1.java .......
java.sql.SQLException: No ResultSet was produced
at sun.jdbc.odbc.JdbcOdbcStatement.executeQuery(JdbcOdbcStatement.java:258)
at BallMoves1.move(BallMoves1.java:378)
at BallMoves1.run(BallMoves1.java:223)
at java.lang.Thread.run(Thread.java:744)*/
You're calling executeQuery on something that isn't a query. But instead of calling execute with the same SQL, you should use a PreparedStatement:
String sql = "insert into highscore (score) values (?)";
try (Connection conn = DriverManager.getConnection("jdbc:odbc:MyDatabase");
PreparedStatement statement = conn.prepareStatement(sql)) {
statement.setInt(1, score);
statement.executeUpdate();
conn.commit();
}
Always use parameterized SQL, instead of plugging the values directly into the SQL - that protects you from SQL injection attacks, conversion errors, and hard-to-read code.
Use a try-with-resources statement (as I have) to automatically close the statement and connection at the end of the block.
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.
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.