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.
Related
I am trying to store the fields from a form in my web-page to a Database in MySQL using JSP. I do not get any errors but i don't see the data in my database when i hit submit. Please help me identify my problem. I have the following codes:
Sign up - New User
<div id="container">
<form action = "insertData.jsp" method = "post">
<table>
<tr><td>E-mail/username:</td><td><input type="text" name="e-mail"></td></tr>
<tr><td>Password:</td><td><input type="password" name="password"></td></tr>
<tr><td>First Name:</td><td><input type="text" name="fName"></td></tr>
<tr><td>Last Name:</td><td><input type="text" name="lName"></td></tr>
<tr><td>Date Of Birth:</td><td><input type="text" name="dateOfBirth"></td></tr>
<tr><td>Account Type:</td><td><input type="text" name="type"></td></tr>
<tr><td></td><td><input type="submit" value="Submit"></td></tr>
</table>
</form>
</div>
</body>
and my JSP Code
<%
Connection con = null;
String email = request.getParameter("e-mail");
String password = request.getParameter("password");
String firstName = request.getParameter("fName");
String lastName = request.getParameter("lName");
String dob = request.getParameter("dateOfBirth");
String accountType = request.getParameter("type");
String queryText = "insert into user values('" + email + "'+'" + password + "','" + firstName + "','" + lastName + "','" + dob + "','" + accountType + "')";
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/project", "root", "B#neswor1");
Statement stat = con.createStatement();
ResultSet rst = stat.executeQuery(queryText);
System.out.println("Data is successfully inserted!");
rst.close();
stat.close();
con.close();
} catch (Exception e) {
}
System.out.println("Success");
%>
Please help me identify what i am missing
The immediate cause of your problem is your insert query:
String queryText = "insert into user values('" + email + "'+'" +
password + "','" + firstName + "','" + lastName + "','" + dob + "','" +
accountType + "')";
If you look closely, there is no comma after the email literal. But you could have avoided this by using a prepared statement:
String sql = "insert into user values (?, ?, ?, ?, ?, ?)";
PreparedStatement ps = con.prepareStatement(insertTableSQL);
ps.setString(1, email);
ps.setString(2, password);
ps.setString(3, firstName);
ps.setString(4, lastName);
ps.setString(5, dob);
ps.setString(6, accountType);
ps.executeUpdate();
Note that using a statement makes it much easier to see how your query string is being built. It also frees you from ugly string concatenation and escaping, which is error prone.
#duffymo pointed out many other potential problem with your code, some of which though should not necessarily cause it to crash. One other problem I see is that your date of birth field is being treated as a string, which it probably should be a date, and you should be inserting into your database as a date.
There are too many things wrong with this code:
Never, ever write scriptlet code in JSPs.
You have an empty catch block in that scriptlet code. If an exception is thrown you'll never know it.
Close resources in finally blocks.
You don't use PreparedStatement. You are asking for a SQL injection attack.
No XSS check.
No validation of input data.
Learn JSTL if you must use JSP.
Be aware that JSP model is vintage 1998. Modern UIs are done using HTML5, CSS3, and Javascript talking to REST services. The world has changed in the last 20 years. Tutorials exist for old technologies, but it doesn't mean they should be your first thought.
I can connect fine in Netbeans using this:
Connection conn = null;
try{
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/librarymangementsystem","root","root");
if(conn!= null)
{
System.out.println("connected");
}
}catch(Exception e)
{
System.out.println("not connected");
}
}
But when it comes to adding data to the columns, i just cant.
try{
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/librarymangementsystem","root","root");
Statement stmt=conn.createStatement();
String Query = "INSERT into librarian_details(username, name, email, password) VALUES("+ uname +", "+ fname +", " + emails + ", " + psword +")";
stmt.executeUpdate(Query);
JOptionPane.showMessageDialog(null, "Success!");
}
Anyone knows the problem?
Updated Problem:
String Query = "insert into book_details(Book_Name, ISBN, Author, Category, >Quantity, BookShelfNo,Row,Column) VALUES('" +bookname + "','" + ISBN + "','" + >AuthorName + "','" + Category + "','" + Quantity + "','" + ?BookShelfNo +"', '" >+ Row + "', '" + Column + "')";
I cant seem to insert any data to Row and Column using this:
String Row = jTextField9.getText();
String Column = jTextField10.getText();
Row and Column Datatype is int.
I guess the username, name, email and password fields are of String type and Data type used while creating the columns username, name, email and password of librarian_details is Varchar .
If so, then you need to update your query string to the below code:
String Query = "INSERT into librarian_details(username, name, email, password)
VALUES('"+ uname +"','"+ fname +"','" + emails + "','" + psword +"')";
If your input String has an apostrophe (') character then you need to add an extra apostrophe (') character as an escape sequence.
For Example:your password is abc'aa
String uname = "abc";
String fname = "xyz";
String emails = "abc#xyz.com";
String psword = "abc''aa";//extra apostrophe (') character added
String Query = "INSERT into librarian_details(username, name, email, password) VALUES('"+ uname+ "','"+ fname+ "','"+ emails+ "','"+ psword+ "')";
Note: Adding extra apostrophe (') to the existing (') character is different than a double quote.
Below code is for your updated query
String bookname ="abc";
String ISBN="qwerty123";
String AuthorName="user3213";
String Category="New";
String Quantity="1";
String BookShelfNo="5";
int Row=1;
int Column=5;
String Query = "insert into book_details(Book_Name, ISBN, Author, Category, Quantity, BookShelfNo,`Row`,`Column`) VALUES('" +bookname + "','" + ISBN + "','" + AuthorName + "','" + Category + "','" + Quantity + "','" + BookShelfNo +"', " + Row + ", " + Column + ")";
stmt.execute(Query);
Note: you are using reserved keywords of sql like Row and Column.
I guess your column names in DB are Book_Name, ISBN, Author, Category, Quantity, BookShelfNo, Row and Column.
Suggestion:
Using PreparedStatement will save your time for writing a query (no need to remember datatype of variable and columns.)
PreparedStatement uses query caching functionality.
Hence, execution is faster than simple statement.
Below code depicts the usage of prepared statement for your query.
//query parameters will be dynamically set
String Query = "INSERT INTO book_details VALUES (?,?,?,?,?,?,?,?)";
//create a Prepared statement using connection object.
PreparedStatement pstmt = con.prepareStatement(Query);
//assign the query parameter values
pstmt.setString(1, bookname);
pstmt.setString(2, ISBN);
pstmt.setString(3, AuthorName);
pstmt.setString(4, Category);
pstmt.setString(5, Quantity);
pstmt.setString(6, BookShelfNo);
pstmt.setInt(7, Row);
pstmt.setInt(8, Column);
//display query string generated by PreparedStatement.
System.out.println("Query: "+pstmt.toString());
//Display result; result=1 means success.
int result = pstmt.executeUpdate();
System.out.println("result: "+result);
Escape the text values or even better - use prepared statements.
String Query = "INSERT into librarian_details(username, name, email, password)
VALUES('"+ uname +"', '"+ fname +"', '" + emails + "', '" + psword +"')";
Prepared statements:
String Query = "INSERT into librarian_details(username, name, email, password)
VALUES(?, ?, ?, ?)";
Concatenating values into a query is unsafe, it opens you up to SQL injection. You need to use a prepared statement instead:
try (PreparedStatement pstmt = connection.prepareStatement(
"INSERT into librarian_details(username, name, email, password) "
+ "VALUES(?, ?, ?, ?)")) {
pstmt.setString(1, uname);
pstmt.setString(2, fname);
pstmt.setString(3, emails);
pstmt.setString(4, psword);
pstmt.executeUpdate();
}
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?
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).
I have a problem, I have a system to add users, I have to make check if this user exist before so that i will not add him again, I retrieved all the name from database into an arraylist.I check first if the array list is empty so that I can add the user else he will check if he exists or not
here is the code
if(names.size() == 0){
dbstatement.executeUpdate("
insert into users (user_name,user_password,user_type)
values ('" + username + "','" + userpassword + "','" + type + "')");
JOptionPane.showMessageDialog(rootPane, "user added successfully");
}
else{
for (int i = 0; i < names.size(); i++) {
if (username.equals(names.get(i))) {
JOptionPane.showMessageDialog(rootPane, "Sorry, this name already exist");
break;
}
}
dbstatement.executeUpdate
("insert into users(user_name,user_password,user_type)
values ('" + username + "','" + userpassword + "','" + type + "')");
}
the problem is when the program found a name exist before he told me and add him, i know the cause of this problem all i want to know where to but else of the if inside for loop, I want him to tell me the user exist onlyy not to add it again
Just use the SQL WHERE clause to see if the username exist. There's absolutely no need to copy the entire DB table into Java's memory.
preparedStatement = connection.prepareStatement("SELECT id FROM users WHERE user_name = ?");
preparedStatement.setString(1, username);
resultSet = preparedStatement.executeQuery();
boolean exist = resultSet.next();
Wrap this in a method like boolean exist(String username) and rearrange your code flow as follows:
if (exist(username)) {
// Show warning message.
} else {
// Insert into DB.
}
Note that PreparedStatement is been used instead of Statement. This prevents your code from SQL injection attacks.
Just call the database with each name to add.
Let the sql try to insert the name. It will either insert or throw a key violation (assuming you have a unique constraint on the name).
If it throws a key violation you know the name is already in the database.
If it does not throw an error then the name was inserted.
Read/decide/write style processing is not the way to make this work. It can still have issues when another process inserts a new name in the time between the read and the write. This means that you still have to check for key violations anyway. If you have to check for key violations anyway you might as well do it right the first time and just try inserting all the names.
if(names.size() == 0){
dbstatement.executeUpdate("
insert into users (user_name,user_password,user_type)
values ('" + username + "','" + userpassword + "','" + type + "')");
JOptionPane.showMessageDialog(rootPane, "user added successfully");
}
else{
if ( names.contains(username) ) {
JOptionPane.showMessageDialog(rootPane, "Sorry, this name already exist");
}
else {
dbstatement.executeUpdate
("insert into users(user_name,user_password,user_type)
values ('" + username + "','" + userpassword + "','" + type + "')");
}
}