Change a line to prepared statement - java

statement.executeUpdate("INSERT INTO LOGIN VALUES(" + jTextField1.getText() + ",'" + jTextField2.getText() + "'," + jTextField3.getText() + ")");
I have this line and I am trying to do this line prepared statement but I am not able to do it.
What I did is this :
PreparedStatement pstmt = con.prepareStatement("UPDATE Login
SET login_id = ? WHERE username = ?");
the sql table is this
CREATE TABLE login(
login_id INTEGER PRIMARY KEY,
username varchar(150) NOT NULL,
password varchar(150) NOT NULL
);

This folwoing code should be encapsuled in a ty catch statment
Also i hope you add a password hashing function to your code, every thing else is very insecure.
PreparedStatement pstmt = con.prepareStatement("INSERT INTO LOGIN VALUES (?,?,?)");
pstmt.setInt (1, Integer.parseInt(jTextField1.getText()));
pstmt.setString (2, jTextField2.getText());
pstmt.setString (3, jTextField2.getText()));
// execute the preparedstatement
pstmt.execute();

observed parameterized object to avoid SQL Injections. just a bunch of security. although that one, you have provided is Okay for learning purposes.

Related

insert json data into postgres database using java program

I'm looking for help to insert json data into postgres table using java program. I have tried with following code but cannot find any data is inserted in to the table. I have very little experience in programming. Can some one help me to modify my program to make it work?
here is my code.
enter code here stmt = c.createStatement();
String sql = "CREATE TABLE jason " +
"(ID INT NOT NULL," +
" NAME json NOT NULL)";
stmt.executeUpdate(sql); //updates the table
//json data----------------
String[] MESSAGE = {"{\"customer_name\": \"John\", \"items\": { \"description\": \"milk\", \"quantity\": 4 } }"};
sql = "INSERT INTO jason (ID,NAME) "
+ "VALUES (1,::MESSAGE );";
stmt.executeUpdate(sql);
You have problem with syntax here, please read this instruction: https://docs.oracle.com/javase/7/docs/api/java/sql/PreparedStatement.html
It's should be:
PreparedStatement pstmt = con.prepareStatement("INSERT INTO jason (ID,NAME) VALUES (1, ?1);");
pstmt.setString(1, yourJsonString)
To use parameters in a statement, you need to use a prepared statement:
java.sql.PreparedStatement stmt = conn.prepareStatement("INSERT INTO jason (ID,NAME) VALUES (1,?)" );
stmt.setString(1, "{\"customer_name\": \"John\", \"items\": { \"description\": \"milk\", \"quantity\": 4 } }");
stmt.executeUpdate();

Can't find an Error in SQL update statement

I'm working in one quiz game. There is question maker window. Which works good for saving question. But when want update one of text Field and press save, than error is happening. something is wrong with syntax?!
void insertCell(String tableNamer, String column, String value, int id) throws ClassNotFoundException, SQLException{
Class.forName("org.h2.Driver");
Connection conn = DriverManager.getConnection("jdbc:h2:file:C:/Users/Juris Puneiko/IdeaProjects/for_my_testings/src/sample/DB/Questions/For_Private/Easy", "Juris", "1");
PreparedStatement ps = conn.prepareStatement("UPDATE ? SET ? = ? where ID = ?");
ps.setString(1, tableNamer);
ps.setString(2, column);
ps.setString(3, value);
ps.setInt(4, id);
ps.executeUpdate();
ps.close();
conn.close();
}
org.h2.jdbc.JdbcSQLException: Syntax error in SQL statement "UPDATE ?[*] SET ? = ? WHERE ID = ? "; expected "identifier"; SQL statement:
UPDATE ? SET ? = ? where ID = ? [42001-196]
What is this >>> [*]?
What does it mean?
String sql = "UPDATE " + tableNamer + " SET " + column + " = ? where ID = ?";
PreparedStatement ps = conn.prepareStatement(sql);
ps.setString(1, value);
ps.setInt(2, id);
ps.executeUpdate();
ps.close();
conn.close();
The placeholders can only be used for values in most SQL databases, not for identifiers like table or column names:
"UPDATE myTable SET myCol = ? where ID = ?" -- OK
"UPDATE ? SET ? = ? where ID = ?" -- not OK
The reason is that those parameters are also used for prepared statements, where you send the query to the database once, the database "prepares" the statement, and then you can use this prepared statement many times with different value parameters. this can improve DB performance because DB can compile and optimize the query and then use this processed form repeatedly - but to be able to do this, it needs to know names of the tables and columns involved.
To fix this, you only leave the ?s in for the values, and you concatenate the tableNamer and column manually:
"UPDATE " + tableNamer + " SET " + column + " = ? where ID = ?"
Keep in mind though that by doing this, tableNamer and column are now potentially vulnerable to SQL injection. Make sure that you don't allow user to provide or affect them, or else sanitize the user input.

data can not save into mysql properly

I am trying to make login time and logout time web application in jsp netbeans. While i try to save logout time into mysql database the date & time save correctly but user name and password both save as null. Please help me to save user name and password correctly to table.
Here is my logout code:
`<%# page import ="java.sql.*" %>
`<%String url="jdbc:mysql://localhost:3306/mysql";`
` String user="root";`
` String password="";`
`Class.forName("com.mysql.jdbc.Driver");`
`Connection con = DriverManager.getConnection(url, user, password);`
`Statement st = con.createStatement();`
`String uname1= request.getParameter("first_name");`
`String pwd = request.getParameter("pass");`
`session.setAttribute("fname", uname1);`
`session.setAttribute("pass", pwd);`
`int i = st.executeUpdate("insert into logut values ('" + uname1 + "','" + pwd + "',now())");`
`if (i > 0) `
`{out.write("<script type='text/javascript'>\n");`
`out.write("alert(' Logout Successfully!!! ');\n");`
`out.write("setTimeout(function({window.location.href='index.jsp'},1000);");`
`out.write("</script>\n");`
`}`
%>`
My database save like this: id= null pass=null and date and time save correctly. help me out. Thank you advance.
There is a typo in your statement. I guess you mean the table logout
"insert into logut values ('" + uname1 + "','" + pwd + "',now())"
But aside this you really have to consider prepared statements.
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, "username");
preparedStatement.setString(3, "password");
preparedStatement.setTimestamp(4, getCurrentTimeStamp());
// execute insert SQL statement
preparedStatement .executeUpdate();
Why prepared Statements:
difference-between-statement-and-preparedstatement
which-is-faster-statement-or-preparedstatement

How to insert in database sqlite3

I'm having trouble inserting data inside my database..this is my codes looks like..
rs = stat.executeQuery("Select * from students;");
while (rs.next()) {
idNum = rs.getString("idNum");
stat.executeUpdate(
"INSERT INTO record VALUES (null,'" + idNum + "','" + descript +
"'," + value + ",'" + user.getText() + "','" + timeStamp + "')"
);
}//while
As you can see I want to insert a data for every student rs = stat.executeQuery("Select * from students;"); and get all their student number idNum = rs.getString("idNum"); this is what inside the students table:
idNum..............Name
11000001.........Leonardo
11000002.........David
11000003.........Robert
11000004.........Anna
11000005.........May
now when I get all their idNum I want them to be inserted inside the table record that will looks like this:
idNum.........descript.........amount........blablablabla
11000001.......Fee...............30
11000002.......Fee...............30
11000003.......Fee...............30
11000004.......Fee...............30
11000005.......Fee...............30
the problem is only the first idNum is being inserted inside the table record like this:
idNum.........descript.........amount........blablablabla
11000001.......Fee...............30
You shoulkd not use the same statement object stat twice: once you are reusing is to perform the update (in your case the insert) it closes the resultset you are looping over.
You can use a single statement to copy the data.
(Using parameters avoids formatting problems with strings containing special characters.)
PreparedStatement ps = conn.prepareStatement(
"INSERT INTO record SELECT NULL, idNum, ?, ?, ?, ? FROM students");
ps.setString(1, descript);
ps.setInt (2, value);
ps.setString(3, user.getText());
ps.setString(4, timeStamp);
ps.execute();
Use an ArrayList to store all idNum from students table. Then loop through the list to insert into record table.

I need help on INSERT statements using JDBC

I need to use an INSERT statement, and 2 of the records in this statement are fields which are calculated in the program, and need to be added to the database.
System.out.println("Executing....");
stmt = conn.createStatement();
String sql;
sql = "INSERT INTO Identities"
+ " VALUES"
+ "('John', 'Smith', '38 Turpington Lane', 'Farnborough', 'Hampshire', 'HA6 7AF', '1990-03-01', PKmod, PKexpo)";
stmt.executeUpdate(sql);
'PKmod' and 'PKexpo' are BigInteger fields whose value is calculated in the java program, how can I add these values to the database?
Thanks for any help! :)
Please do not insert sqls this way. Use prepared statement. Change your sql to use "?" markers instead of concatenating values.
It depends on the DBMS. For mysql perhaps BIGINT should suffice?
http://dev.mysql.com/doc/refman/5.0/en/numeric-type-overview.html
You need to concatenate the string!!!!
So do as follows:
sql = "INSERT INTO Identities"
+ " VALUES"
+ "('John', 'Smith', '38 Turpington Lane', 'Farnborough', 'Hampshire', 'HA6 7AF', '1990-03-01',"+ PKmod+", "+PKexpo+")";
System.out.println("Executing....");
stmt = conn.createStatement();
String sql;
sql = "INSERT INTO Identities"
+ " VALUES"
+ "('John', 'Smith', '38 Turpington Lane', 'Farnborough', 'Hampshire', 'HA6 7AF', '1990-03-01', "
+ PKmod
+ ", "
+ PKexpo
+ ")";
stmt.executeUpdate(sql);
// First Check That PKmod & PKexpo values are not Zero Or Null.
System.out.println("Executing....");
String sql = "INSERT INTO Identities"
+ " VALUES"
+ "('John', 'Smith', '38 Turpington Lane', 'Farnborough', 'Hampshire', 'HA6 7AF', '1990-03-01'," + PKmod + "," + PKexpo +")";
PreparedStatement pStmt = null;
pStmt = con.prepareStatement(sql);
pStmt.executeUpdate();
closePreparedStatement(pStmt);

Categories

Resources