I have seen lot of answers over here regarding my question, but can not find solution for it. I am reading a excel file and storing in mysql database. This is my code
PreparedStatement sql_statement = (PreparedStatement) con
.prepareStatement("insert into medtest(FMCODE,FLAG,MCODE,EMPNO,NAME,ADDRESS1,ADDRESS2,ADDRESS3,BALANCE,HOSPITAL_O,HOSPITAL_I,NURSING,GENERAL,PRIVATE,SPLCODE,BKCD,ACCOUNT_NO) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)");
wb = WorkbookFactory.create(new File(filePath));
// System.out.println(wb.getSheetName());
Sheet mySheet = wb.getSheetAt(0);
for (Row row : mySheet) {
String fmcode = row.getCell(0).getStringCellValue();
String flag = row.getCell(1).getStringCellValue();
int mcode = (int) row.getCell(2).getNumericCellValue();
String empno = row.getCell(3).getStringCellValue();
String name = row.getCell(4).getStringCellValue();
String address1 = row.getCell(5).getStringCellValue();
String address2 = row.getCell(6).getStringCellValue();
String address3 = row.getCell(7).getStringCellValue();
double balance = (double) row.getCell(8).getNumericCellValue();
double hospital_o = (double) row.getCell(9)
.getNumericCellValue();
double hospital_i = (double) row.getCell(10)
.getNumericCellValue();
double nursing = (double) row.getCell(11).getNumericCellValue();
double general = (double) row.getCell(12).getNumericCellValue();
double prvte = (double) row.getCell(13).getNumericCellValue();
String splcode = row.getCell(14).getStringCellValue();
String bkcd = row.getCell(15).getStringCellValue();
String account_no = row.getCell(16).getStringCellValue();
String sql = "insert into medtest values('" + fmcode + "','"
+ flag + "','" + mcode + "','" + empno + "','" + name
+ "','" + address1 + "','" + address2 + "','"
+ address3 + "','" + balance + "','" + hospital_o
+ "','" + hospital_i + "','" + nursing + "','"
+ general + "','" + prvte + "','" + splcode + "','"
+ bkcd + "','" + account_no + "')";
PreparedStatement ps = (PreparedStatement) con
.prepareStatement(sql);
ps.executeUpdate();
When i am inserting my excel file into database getting the below exception, how to solve it.
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
'S DENTAL CLINIC','KINGSWAY CAMP, DELHI.','0.0','0.0','0.0','0.0','0.0','0.0','nu'
at line 1
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:526)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:406)
...
The error is pointing to the ps.executeUpdate(); line.
Replace
sql_statement.executeUpdate() with ps.executeUpdate().
You are trying to execute preparedstatement sql_statement without setting the parameters. Either you can set the parameters and invoke sql_statement.executeUpdate() or simply replace sql_statement.executeUpdate with ps.executeUpdate().
The error message tells you exactly what's wrong - your query is broken around 'S DENTAL CLINIC'. My guess is this is part of a larger string, like BOB'S DENTAL CLINIC - do you see the problem now? The string you're trying to insert into the query contains a ', breaking the rest of the query.
The right thing to do here, as already suggested, is to use Prepared Statements. You should never construct dynamic SQL statements via string concatenation; not only does it risk these sort of syntax errors, but it's also the cause of SQL injection attacks.
Some related questions:
How to use prepared statement
When should we use a PreparedStatement instead of a Statement?
How can prepared statements protect from SQL injection attacks?
Related
I am trying to compare the screen values input against the value stored in DB. Currently i am trying this code:
cell = sheet.getRow(i).getCell(2);
Class.forName("com.mysql.cj.jdbc.Driver");
Connection con = DriverManager.getConnection ("jdbc:mysql://madison-dev.czr6vej2htnn.us-east-1.rds.amazonaws.com:3306/madisondb","madisonadmin","t4xuw94$");// + "databasename=madison-dev.czr6vej2htnn.us-east-1.rds.amazonaws.com";
Statement st = con.createStatement();
ResultSet Rs = st.executeQuery("select name, zipcode, state, city, street from business_master where user_id =(\r\n" +
"select id\r\n" +
"from user_master\r\n" +
"where email = 'cell.getStringCellValue()') \r\n");
while (Rs.next()) {
// System.out.println(Rs.getString(1) + " " + Rs.getString(2) + " " + Rs.getString(3) + " "
// + Rs.getString(4) + " " + Rs.getString(5));
System.out.println(Rs.getString(0));
}
The screen is not showing any values.. and when i am trying to print System.out.println(Rs.getString(3)) outside of the loop it gives me an error
java.sql.SQLException: Illegal operation on empty result set.
You are trying to find all the rows where the email address is literally the text 'cell.getStringCellValue()' rather than the value returned by that method.
Whilst you code assemble your query string, that lays you open to SQL injection attacks. Use a prepared statement instead
PreparedStatement st = con.prepareStatement(
"select name, zipcode, state, city, street from business_master where user_id =(" +
"select id " +
"from user_master " +
"where email = ?)");
st.setString(1, cell.getStringCellValue());
ResultSet Rs = st.executeQuery();
I know, for PreparedStatement I need to have the SQL expression fed into the PreparedStatement like this
String updateStatement =
"update " + dbName + ".COFFEES " +
"set TOTAL = TOTAL + ? " +
"where COF_NAME = ?";
However, can I feed the update statement with the full where clause without "?"
For example
String updateStatement =
"update " + dbName + ".COFFEES " +
"set TOTAL = TOTAL + ? " +
"where COF_NAME = 'aaa";
It is just cause I get the where as a parameter in my function, and I don't think it would be efficient to parse the string to break it up.
The purpose of using prepared statement is to have dynamic variables, but as you're asking if you can hard code the whole where clause, yes you can hard code it.
I created a registered form of user information with JSP. I want to insert user data into a table with userinfo in postgre database after submitting form. But instead of adding data into this table, it gives me errors. Please help me!
<%
String fname = request.getParameter("fname");
String lname = request.getParameter("lname");
String email = request.getParameter("email");
String user = request.getParameter("uname");
String pwd = request.getParameter("pass");
String pwd2 = request.getParameter("pass2");
Class.forName("org.postgresql.Driver");
Connection con = DriverManager.getConnection("jdbc:postgresql://127.0.0.1:5432/UserInformation", "postgres", "123456789");
PreparedStatement st = con.prepareStatement("insert into userinfo(firstname, lastname, email, username, password) VALUES ('" + fname + "','" + lname + "','" + email + "','" + user + "','" + pwd + "'");
//ResultSet rs;
int i = st.executeUpdate();
if (i > 0) {
response.sendRedirect("welcome.jsp");
} else {
response.sendRedirect("login.jsp");
}
%>
The output is:
org.postgresql.util.PSQLException: ERROR: syntax error at end of input
Position: 142
(This is a comment, but i can't comment because don't have 50 points)
You must know, that scriptlets are a bad practice when you work with JSP. When code keep in mind the software development principles, like DRY (don't repeat yourself), SRP (single responsibility principle) and more. You have mixed your views with domain model, never do that. The only thing that you get when doing this is:
Poor scalability
Poor maintenance
Spaghetti code
So, you need to re-structure your application by adding some layers (controllers and model).
Create a access data abstract layer for communication with your data (eg., dao, repository).
Create a controller for yours views.
Use JSTL in your views to avoid scriptlets.
You have an sql syntax error remove the comma and single quotation(,') at the end of your insert query
int i = st.executeUpdate("insert into userinfo(firstname, lastname, email, username, password, city, province, country) VALUES ('" + fname + "','" + lname + "','" + email + "','" + user + "','" + pwd + "','" + city + "','" + province + "','" + country + "'");
In addition use PreparedStatement instead of Statement to avoid sql injection.
`I am having a problem with doing a PreparedStatement for Java ODBC MySQL. It seems to be cutting off the query, and giving a syntax error. I am not sure how to proceed, as I am only learning Java SQL at this point. I can't really do a self contained example because the problem involves databases, and it would get quite big.
The code with the problem is this..
public void insertEntry(
Hashtable<String, String> strings,
Hashtable<String, Integer> integers,
Date created, Date paid, boolean enabled)
throws ClassNotFoundException, SQLException {
Class.forName("com.mysql.jdbc.Driver");
String dburl = "jdbc:mysql://" + dbHost + "/" + dbName +
"?user=" + dbUser + "&password=" + dbPass;
connect = DriverManager.getConnection(dburl);
ps = connect.prepareStatement("INSERT INTO " + dbName + ".users INSERT " +
"enabled=?, username=?, created=?, paid=?, alias=?, password=?, " +
"email=?, bitmessage=?, torchat=?, reputation=?," +
"privacy=?, fpmport=?, fpm-template=? ;");
java.sql.Date SQLcreated = new java.sql.Date(created.getTime());
java.sql.Date SQLpaid = new java.sql.Date(paid.getTime());
System.out.println("Debug: SQLpaid = " + SQLpaid.toString());
ps.setBoolean(1, enabled);
ps.setString(2, strings.get("username"));
ps.setDate(3, SQLcreated);
ps.setDate(4, SQLpaid);
ps.setString(5, strings.get("alias"));
ps.setString(6, strings.get("password"));
ps.setString(7, strings.get("email"));
ps.setString(8, strings.get("bitmessage"));
ps.setString(9, strings.get("torchat"));
ps.setInt(10, integers.get("reputation"));
ps.setInt(11, integers.get("privacy"));
ps.setInt(12, integers.get("fpmport"));
ps.setString(13, strings.get("fpm-template"));
ps.executeUpdate();
ps.close();
connect.close();
resultSet.close();
}
I get the following output when trying to use this method...
Debug: SQLpaid = 1990-03-21
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorEx ception: 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 'INSERT enabled=0, username='default_username', created='2000-03-21', paid='1990-' at line 1
at sun.reflect.NativeConstructorAccessorImpl.newInsta nce0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInsta nce(NativeConstructorAccessorImpl.java:57)
at sun.reflect.DelegatingConstructorAccessorImpl.newI nstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Construc tor.java:532)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:41 1)
at com.mysql.jdbc.Util.getInstance(Util.java:386)
at com.mysql.jdbc.SQLError.createSQLException(SQLErro r.java:1054)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.ja va:4237)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.ja va:4169)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:26 17)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java :2778)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionIm pl.java:2834)
at com.mysql.jdbc.PreparedStatement.executeInternal(P reparedStatement.java:2156)
at com.mysql.jdbc.PreparedStatement.executeUpdate(Pre paredStatement.java:2441)
at com.mysql.jdbc.PreparedStatement.executeUpdate(Pre paredStatement.java:2366)
at com.mysql.jdbc.PreparedStatement.executeUpdate(Pre paredStatement.java:2350)
at database.Users.insertEntry(Users.java:297)
at test.dbUsers.main(dbUsers.java:95)
i think your doing some mistake in your code:
these are following as:
1. your mention INSERT and you should must change like SET
2. your adding the ;in your SQL Query you should remove that.
your code:
ps = connect.prepareStatement
("INSERT INTO " + dbName + ".users INSERT " #look here error to change 'set' +
"enabled=?, username=?, created=?, paid=?, alias=?, password=?, " +
"email=?, bitmessage=?, torchat=?, reputation=?," +
"privacy=?, fpmport=?, fpm-template=? ; " #remove this semicolon(;));
you should must change like as:
ps = connect.prepareStatement
("INSERT INTO " + dbName + ".users SET " +
"enabled=?, username=?, created=?, paid=?, alias=?, password=?, " +
"email=?, bitmessage=?, torchat=?, reputation=?," +
"privacy=?, fpmport=?, fpm-template=? ");
Change:
INSERT INTO " + dbName + ".users INSERT "
To:
INSERT INTO " + dbName + ".users SET "
Refer to:
MySQL: INSERT Syntax
INSERT [LOW_PRIORITY | DELAYED | HIGH_PRIORITY] [IGNORE]
[INTO] tbl_name
[PARTITION (partition_name,...)]
SET col_name={expr | DEFAULT}, ...
[ ON DUPLICATE KEY UPDATE
col_name=expr
[, col_name=expr] ... ]
I've created this little quiz for a school project using Java and MySQL. Now My project runs fine but as an experiment i tried to add images in my question. The Question jFrame takes the question and all options directly from a database called ques having 8 columns last of which is "path" which is a varchar(500). Here is my Java code to add questions :-
try {
Class.forName("java.sql.Driver");
Connection con = (Connection) DriverManager.getConnection(jdbcurl, user, pass);
Statement st = con.createStatement();
ResultSet rt = st.executeQuery("SELECT qno from ques order by qno desc limit 1");
// get last qno primary key
for (; rt.next(); ) {
qno = (Integer) rt.getObject(1); // save qno as int
}
nqno = qno + 1; // create new qno
if (path == null){
String query1 = "insert into ques values (" + nqno + ",'" + question + "','" + ans1 + "','" + ans2 + "','"
+ ans3 + "','" + ans4 + "','" + ca + "',null);"; // ca is correct answer and null is path
Statement st1 = con.createStatement();
st1.executeUpdate(query1);
System.out.println("query : "+query1);
JOptionPane.showMessageDialog(this, "Question added successfully! Without Image");}
else {
String query1 = "insert into ques values (" + nqno + ",'" + question + "','" + ans1 + "','" + ans2 + "','"
+ ans3 + "','" + ans4 + "','" + ca + "','"+path+"');";
System.out.println("query :" +query1);
Statement st1 = con.createStatement();
st1.executeUpdate(query1);
JOptionPane.showMessageDialog(this, "Question added successfully! with image");
}
} catch (Exception e) {
JOptionPane.showMessageDialog(this, "Error in code");
The query sent was
query :insert into ques values (12,'123','123','123','123','123','123','F:\JavaQuiz\src\javaquiz\About.png');
All okay, no exception handled.
But in the SQL the path is saved so :- F:JavaQuizsrcjavaquizAbout.png
The database omits the backslashes. I want it not to do so. So that later I can call this link in my Question.java
Please.. Any suggestion?
(I'm sorry I'm new to programming so sorry if this is a dumb question)
User PreparedStatement instead of Statement and set the parameters. This will set the correct String with required escape characters.
String query1 = "insert into ques values (?,?,?,?,?,?,?,?)";
PreparedStatement ps=connection.prepareStatement(query1);
ps.setInt(1,nqno);
ps.setString(2,question);
ps.setString(3,ans1);
ps.setString(4,ans2);
ps.setString(5,ans3);
ps.setString(6,ans4);
ps.setString(7,ca);
ps.setString(8,path);
ps.executeUpdate();
and do the try..catch for exceptions.
In java (and C,C++,C#) string the backslash character is a special "escape" character. You need to use \\ to represent a backslash, or change your insert to use parameters using prepared statements rather then be a string.
See Java Character Escape Code Reference
(Or just change your path to use / slashes).