Insert values to mysql table via Java GUI - java

I'm working with java and mysql and I'm facing a problem. I'm trying to create an app with GUI to insert data into mysql table and this is the code :
public void insertuser(String fullname,String salary,String adress,String username,String password) throws SQLException
{
openconnection();
//openconnection method works well
String queryInsert =
"INSERT INTO hema.employee (Emp_name,Emp_salary,Adress,UserName,PassWord)"
+ "VALUES ('"+fullname+"','"+salary+"','"+adress+"','"+username+"','"+password+"')";
Statement stm=(Statement) con.createStatement();
ResultSet rs;
stm.executeQuery(queryInsert);
}
and in the JFrame class I call this method using this code :
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
try {
String NAME =jTextField1.getText();
String SALARY =jTextField2.getText() ;
String ADRESS =jTextField3.getText();
String USER =jTextField4.getText();
String PASS =jPasswordField1.getText();
Employee emp=new Employee();
emp.insertuser(NAME, SALARY, ADRESS, USER, PASS);
} catch (SQLException ex) {
Logger.getLogger(Register.class.getName()).log(Level.SEVERE, null, ex);
}
}
and the first error I have is:
java.sql.SQLException: Can not issue data manipulation statements with executeQuery().

The executeQuery() method is only for executing select statements. For insert, update, and delete statements, you should use the executeUpdate() method.
Executes the given SQL statement, which may be an INSERT, UPDATE, or DELETE statement or an SQL statement that returns nothing, such as an SQL DDL statement.

String sqlInsert =
"INSERT INTO hema.employee (Emp_name,Emp_salary,Adress,UserName,PassWord)"
+ "VALUES (?, ?, ?, ?, ?)";
try (PreparedStatement stm = con.prepareStatement(sqlInsert)) {
stm.setString(1, fullname);
stm-setBigDecimal(2, new BigDecimal(salary));
stm.setString(3, adress);
stm.setString(4, username);
stm.setString(5, password);
int updateCount = stm.executeUpdate(); // 1 when inserted 1 record
} // Closes stm
The error, that for INSERT, DELETE. UPDATE and such executeUpdate should be used is given already.
Also close the statement, for example use the above try-with-resources.
Important is to use a prepared statement. This is a security measure (against SQL injection), but also escapes quotes and backslashes in the values
Another advantage of a prepared statement is that you could reuse it; not so necessary here.
But more important is the type safe setting of fields: I altered the salary field to use BigDecimal, appropriate for numeric values with decimals (SQL column type DECIMAL or so).

Related

How to set variables into a JDBC statement?

It works when i try to insert variables for example :
String insertStr="INSERT INTO table1(username1,password1) VALUES(\"john\",\"password\")";
but unable to insert using variable
String a=username.getText();
String b=password.getText();
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/java_db1","root","");
Statement stmt=con.createStatement();
String insertStr="INSERT INTO table1(username1,password1) VALUES(a,b);";
stmt.executeUpdate(insertStr);
} catch (Exception e) { }
Use [PreparedStatement][1] instead of your way, because your way can be a victim of SQL Injection or Syntax errors :
String insertStr = "INSERT INTO table1(username1,password1) VALUES(?, ?)";
try (PreparedStatement pst = con.prepareStatement(insertStr)) {
pst.setString(1, a);
pst.setString(2, b);
pst.executeUpdate();
}
For reason of security I don't suggest to get password with getText(), instead use getPassword(), so you can use :
pst.setString(1, username.getText());
pst.setString(2, new String(passwordField.getPassword()));
Take a look at this :
getText() vs getPassword()
Why getText() in JPasswordField was deprecated?
[1]: https://docs.oracle.com/javase/8/docs/api/java/sql/PreparedStatement.html
Since you are inserting "a" and "b" as String, not their variable values.
String insertStr="INSERT INTO table1(username1,password1) VALUES("+a+","+b+");";
should do it, but I would recommend to use a prepared statement here: https://docs.oracle.com/javase/tutorial/jdbc/basics/prepared.html
The most common way to insert variable values into sql is to use the PreparedStatement Object
With this object, you can add variable values into a SQL Query without fearing of SQL injection.
Here an example of PreparedStatement :
//[Connection initialized before]
String insertStr="INSERT INTO table1(username1,password1) VALUES(?,?);";
PreparedStatement myInsert = myConnectionVariable.prepareStatement(insertStr); // Your db will prepare this sql query
myInsert.setString(1, a); //depending on type you want to insert , you have to specify the position of your argument inserted (starting at 1)
myInsert.setString(2, b); // Here we set the 2nd '?' with your String b
myInsert.executeUpdate(); // It will returns the number of affected row (Works for UPDATE,INSERT,DELETE,etc...)
//You can use executeQuery() function of PreparedStatement for your SELECT queries
This is safer than using String concatenation like this : VALUES("+a+","+b+");
Take a look at Java Doc for more information ;)

How to inject a SQL command to drop a table in java

My java code for SQL Query is
String sqlSt="INSERT INTO users(id,name,place) values ("+null+",'"+request.getParameter("name")+"','"+request.getParameter("place")+"');";
I have tried out
name= a'); DROP TABLE users; --
as well as
place =a'); DROP TABLE users; --
but it returns an Ecxeption as below
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 'DROP TABLE users; --','chennai')' at line 1
Note: when i tried the same in mysql command line. It worked!!!! i don't know what happens in jdbc
The real problem is actually JDBC, it only allows one sql if you dont tell it otherwise.
Look at this question for more info:
Multiple queries executed in java in single statement
But also i would try this instead, name =
a',''); DROP TABLE users; --
Since you specificed 3 columns in your insert:
(id,name,place)
You need to provide 3 values for the sql to be valid, not just 2.
Also you can sent the text null, sending a java null value is not necessary and i am not even sure how that works. I think this might be better:
String sqlSt="INSERT INTO users(id,name,place) values (null,'"+request.getParameter("name")+"','"+request.getParameter("place")+"');";
Instead of null, use an empty string ''
String sqlSt = "INSERT INTO users(id, name, place) values ('', '" + request.getParameter("name") + "', '" + request.getParameter("place") + "');";
It's better to use prepared statements to avoid confusion.
String sqlSt = "INSERT INTO users(id, name, place) values ('', ?, ?)";
PreparedStatement ps = null;
try {
ps = connection.prepareStatement(query);
ps.setString(1, request.getParameter("name"));
ps.setString(2, request.getParameter("place"));
ps.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
} finally {
ps.close();
}
The real problem is with your Query. It is better to use a PreparedStatement for executing a query.
Your Code should be :
String sqlSt="INSERT INTO users(id,name,place) values (?,?,?)";
PreparedStatement pstmt = null;
try{
pstmt = dbConnection.prepareStatement(sqlSt);
pstmt.setString(1,null);
pstmt.setString(2,request.getParameter("name"));
pstmt.setString(3,request.getParameter("place"));
pstmt.executeUpdate();
}catch (Exception e) {
e.printStackTrace();
} finally {
pstmt.close();
}
If you don't want to use a PreparedStatement, just remove last ; from your query.
So your query will be :
String sqlSt="INSERT INTO users(id,name,place) values ("+null+",'"+request.getParameter("name")+"','"+request.getParameter("place")+"')";

MySQL upsert (ON DUPLICATE KEY) using JDBC Prepared Statement

I am trying to write a method to have an UPSERT functionality with a prepared statement in java. The code looks as follows;
public boolean addUserDeviceToken(String userid, String password, String deviceToken, Connection connection) {
String addDeviceToken = "INSERT INTO swiped.Users (userid, password, deviceToken) VALUES( ?, ?, ?) ON DUPLICATE KEY UPDATE devicetoken = ?";
boolean result = false;
ResultSet rs = null;
PreparedStatement st = null;
try {
st = connection.prepareStatement(addDeviceToken);
st.setString(1, userid);
st.setString(2, password);
st.setString(3, deviceToken);
st.setString(4, deviceToken);
What I am unsure of is whether i use st.executeQuery(); or st.executeUpdate(); as surely it depends on the condition of the duplicate key?
What is the correct approach
thanks
You don't want to get a resultSet, there's no result apart the number of insertions or updates, simply use executeUpdate.
Extract from the javadoc :
Executes the given SQL statement, which may be an INSERT, UPDATE, or DELETE statement

quotation marks in string parameter insert 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.

Java Prepared statement not executing

I have created a small 3 tier program, consisting of : front end -> servlet -> database.
Front end I enter some details into a form. They are passed to a servlet, which will render some HTML and display the values entered into the form, while also calling a class DatabaseHelper. The DatabaseHelper then connects and inserts these same values into a table.
I know the values are being passed to the servlet class ok, as they are being displayed in the HTML. So the problem must lie within the prepared statement. Problem is, I cannot see any fault with the statement itself. When I query the table itself, there is no data there.
Database connectivity is functional, as I can insert values into a database using hardcoded statements, just not a prepared statement.
Here is a look at the statement Im using. Any advice is much appreciated.
public void addRegisterDetails(String name, String email, String country, String password, ){
try{
String driver = "com.mysql.jdbc.Driver";
Class.forName(driver).newInstance();
// Make db connection
con = DriverManager.getConnection(url, USERNAME, PASSWORD);
st = con.createStatement();
String query = " INSERT INTO user_information (name, email, country, password)" + " VALUES (?, ?, ?, ?)";
PreparedStatement preparedStmt = con.prepareStatement(query);
preparedStmt.setString (1, name);
preparedStmt.setString (2, email);
preparedStmt.setString (3, country);
preparedStmt.setString (4, password);
preparedStmt.execute();
}catch(ClassNotFoundException ex) {
System.out.println(ex);
}catch(Exception e){
e.printStackTrace();
}
}
Table definition
id| name | email | country | password
all VARCHAR except the id, which is type INT.
You should invoke the method executeUpdate() on the statement object.
Also, I don't see any call to commit the data, any transaction handling. It's fine if you skipped that piece of code for the purpose of this question; otherwise it's quite an important step ( commit if all goes well, rollback for exception scenarios)
Use executeUpdate for database write operations:
preparedStmt.executeUpdate();
Answer: The database ID was not set to auto increment. For some reason this does not allow you to then insert data to table. Thanks to ChadNC for pointing this out.
Also, why st = con.createStatement();?
And why do you have a leading space in your query?
String query = " INSERT INTO user_information (name, email, country, password)"
+ " VALUES (?, ?, ?, ?)";
This leading space may or may not matter...
Lastly, you should be closing your connection when you're through with it, using try-with-resources or a finally block.

Categories

Resources