Insert integer from a jsp form into a database table? - java

See my code below...
//connect
//reading params from the form
String name = request.getParameter("name");
String year_prime = request.getParameter("year");
int year = Integer.parseInt(year_prime);
//inserting the params into table Students
stmt.executeUpdate("insert into students(name,year) values('"+name+"', year)");
//close connection
I am trying to get the year value, which is an int, and insert it into a database table. However I am getting an error, and the INSERT methods only seem to work with Strings. Could someone please help me with this problem.

You should have to use PreapredStatement. From your post I can see you have incorrect value for VALUES() set.
stmt.executeUpdate("insert into students(name,year) values ('" + name + "'," + year ")");
It will be easy and safe to perform database operation with PreparedStatement:
String sql="insert into students(name,year) values (?,?)";
PreparedStatement statement=cn.prepareStatement(sql);
statement.setString(1,name);
statement.setInt(2,year);
statement.executeUpdate();

The following links might help you with the basics and also with a working example:
http://www.tutorialspoint.com/jdbc/jdbc-statements.htm
http://www.tutorialspoint.com/jdbc/statement-object-example.htm
Though I won't recommend and it is also not a general practice to include JDBC connection code in JSP, why? Here is the Servlets and Jsp Best Practices for you.
Hope this helps.

Use a PreparedStatement instead of a regular Statement. Also, use executeQuery() instead of executeUpdate().

Related

preparestatement with name [duplicate]

I was wondering if there was any way to specify returned column names using prepared statements.
I am using MySQL and Java.
When I try it:
String columnNames="d,e,f"; //Actually from the user...
String name = "some_table"; //From user...
String query = "SELECT a,b,c,? FROM " + name + " WHERE d=?";//...
stmt = conn.prepareStatement(query);
stmt.setString(1, columnNames);
stmt.setString(2, "x");
I get this type of statement (printing right before execution).
SELECT a,b,c,'d,e,f' FROM some_table WHERE d='x'
I would, however, like to see:
SELECT a,b,c,d,e,f FROM some_table WHERE d='x'
I know that I cannot do this for table names, as discussed
here, but was wondering if there was some way to do it for column names.
If there is not, then I will just have to try and make sure that I sanitize the input so it doesn't lead to SQL injection vulnerabilities.
This indicates a bad DB design. The user shouldn't need to know about the column names. Create a real DB column which holds those "column names" and store the data along it instead.
And any way, no, you cannot set column names as PreparedStatement values. You can only set column values as PreparedStatement values
If you'd like to continue in this direction, you need to sanitize the column names (to avoid SQL Injection) and concatenate/build the SQL string yourself. Quote the separate column names and use String#replace() to escape the same quote inside the column name.
Prepare a whitelist of allowed column names. Use the 'query' to look up in the whitelist to see if the column name is there. If not, reject the query.
For MySQL prepared statements with NodeJS (mysqljs/mysql), what you need to know is that ? is for values, but if you need to escape column names, table names etc, use ?? instead.
Something like this will work:
SELECT ??, ??, ?? FROM ?? WHERE ?? < ?
Set values to ['id', 'name', 'address', 'user', 'id', 100]
I think this case can't work because the whole point of the prepared statement is to prevent the user from putting in unescaped query bits - so you're always going to have the text quoted or escaped.
You'll need to sanitize this input in Java if you want to affect the query structure safely.
Use sql injection disadvantage of Statement Interface as advantage.
Ex:
st=conn.createStatement();
String columnName="name";
rs=st.executeQuery("select "+ columnName+" from ad_org ");
public void MethodName(String strFieldName1, String strFieldName2, String strTableName)
{
//Code to connect with database
String strSQLQuery=String.format("select %s, %s from %s", strFieldName, strFieldName2, strTableName);
st=conn.createStatement();
rs=st.executeQuery(strSQLQuery);
//rest code
}
Below is the solution in java.
String strSelectString = String.format("select %s, %s from %s", strFieldName, strFieldName2, strTableName);

Can I pass column names in this manner?

query = "UPDATE personal_details SET '" + field + "' = '" + edit + "' WHERE associate_id = '" + associate_id + "'";
Here my table name is personal_details and I am taking the table column name as a parameter in the variable filed and its new value in edit. This code is in Java. and the database I'm accessing is in PostgreSQL.
Although you can build string using plain concatenation, the more recommended ways are:
Use StringBuilder/StringBuffer when you build strings to optimize program speed, specially if you concatenate strings inside loop;
The most recommended way is to use PreparedStatement and fill parameter values. See: http://docs.oracle.com/javase/tutorial/jdbc/basics/prepared.html
Don't construct queries like this! It is bad practice due to security issues, as #Rory pointed out. Instead use a PreparedStatement with parameters, for example:
String updateTableSQL = "UPDATE DBUSER SET USERNAME = ? WHERE USER_ID = ?";
PreparedStatement preparedStatement = dbConnection.prepareStatement(updateTableSQL);
preparedStatement.setString(1, "mkyong_new_value");
preparedStatement.setInt(2, 1001);
// execute insert SQL stetement
preparedStatement .executeUpdate();
(Taken from mkyong)
You are constructing a string that contains the query. The database has no idea how the string is being constructed. Eventually, you'll just pass the string where it will be parsed, compiled, and executed. So yes, you can construct the query this way.
You cannot pass column names or table names as parameters into a query. It is recommended that you pass other values as parameters into the query.

How to access MySQL field names while reading records

I'm using this code to get data from a mysql database:
ResultSet rs= statement.executeQuery(" select id, email from table ");
System.out.println( rs.getInt(1) );
System.out.println( rs.getString(2) );
I want to access field names by their names instead of numerical values as shown above.
Is something like this possible/available:
rs.getValue("id");
I think rs.getInt("id") will work as you'd expect it to.
Also, see ResultSetMetaData.
The method getInt(String columnLabel) in the ResultSet interface will accept a string with the column name, so in your case it will be getInt("id"); and yes it will work.
Cheers.

How can I avoid entering duplicate entries in my MySQL database?

So, what I'm trying to do here is check the user table in my users mySQL database for duplicate entries in the username row, before inserting a new username. Here's an example of my code. Currently, the results ResultSet does not do anything and I'm not exactly sure how to implement it into the IF statement that follows. And yes, I have the catches for the try, just not in this example. Sorry if this is a rather simple question, I just started programming with Java last week. Also, it's my first question on here and I definitely appreciate the help.
try{
String sequel = ("SELECT username FROM `users`.`user`");
PreparedStatement userNameInfo = conn.prepareStatement(sequel);
userNameInfo.executeQuery(sequel);
ResultSet results = userNameInfo.getResultSet();
if (sequel.equals("")) {
conn.setAutoCommit(false);
String sql = "INSERT INTO `users`.`user`(`username`,`password`,`email`) VALUES('" + newusername +"', '" + newpassword + "', '" + newemail +"')";
PreparedStatement prest = conn.prepareStatement(sql);
prest.executeUpdate(sql);
conn.commit();
conn.close();
System.out.println("Added Successfully!");
}
else {
System.out.println("Add failed!");
}
}
So I think what you trying to do - and should do I think, is select if the username is in the table then add or not. So the sql needs to be like:
select username from users where username = ?
then set the param in the query. See docs here:
http://docs.oracle.com/javase/6/docs/api/java/sql/PreparedStatement.html
You then need to check what is in the resultset after the query, and see if anything is in there. The API docs for this will be in about the same place as the PreparedStatement docs.
Adding a constraint in the db will also give you a belt and braces.
Hope this helps
When you define your SQL table, you can define some items to be unique.
So in your example, if you want usernames to be unique, you would add:
UNIQUE(username)
to your table declaration.
If you want the pair username / email to be unique, you would add:
UNIQUE(username, email)
The documentation is here
Have you created the primary key in the table? A primary key automatically prevents duplicate values.
If you want to prevent duplicate usernames, then make your username column the primary key.
Umm, I am not a java guy. But this may help you.
You can retrieve the row count of the first result set after the query executes. If the row count is equal to 0, that means database does not contain a similar record.

Variable column names using prepared statements

I was wondering if there was any way to specify returned column names using prepared statements.
I am using MySQL and Java.
When I try it:
String columnNames="d,e,f"; //Actually from the user...
String name = "some_table"; //From user...
String query = "SELECT a,b,c,? FROM " + name + " WHERE d=?";//...
stmt = conn.prepareStatement(query);
stmt.setString(1, columnNames);
stmt.setString(2, "x");
I get this type of statement (printing right before execution).
SELECT a,b,c,'d,e,f' FROM some_table WHERE d='x'
I would, however, like to see:
SELECT a,b,c,d,e,f FROM some_table WHERE d='x'
I know that I cannot do this for table names, as discussed
here, but was wondering if there was some way to do it for column names.
If there is not, then I will just have to try and make sure that I sanitize the input so it doesn't lead to SQL injection vulnerabilities.
This indicates a bad DB design. The user shouldn't need to know about the column names. Create a real DB column which holds those "column names" and store the data along it instead.
And any way, no, you cannot set column names as PreparedStatement values. You can only set column values as PreparedStatement values
If you'd like to continue in this direction, you need to sanitize the column names (to avoid SQL Injection) and concatenate/build the SQL string yourself. Quote the separate column names and use String#replace() to escape the same quote inside the column name.
Prepare a whitelist of allowed column names. Use the 'query' to look up in the whitelist to see if the column name is there. If not, reject the query.
For MySQL prepared statements with NodeJS (mysqljs/mysql), what you need to know is that ? is for values, but if you need to escape column names, table names etc, use ?? instead.
Something like this will work:
SELECT ??, ??, ?? FROM ?? WHERE ?? < ?
Set values to ['id', 'name', 'address', 'user', 'id', 100]
I think this case can't work because the whole point of the prepared statement is to prevent the user from putting in unescaped query bits - so you're always going to have the text quoted or escaped.
You'll need to sanitize this input in Java if you want to affect the query structure safely.
Use sql injection disadvantage of Statement Interface as advantage.
Ex:
st=conn.createStatement();
String columnName="name";
rs=st.executeQuery("select "+ columnName+" from ad_org ");
public void MethodName(String strFieldName1, String strFieldName2, String strTableName)
{
//Code to connect with database
String strSQLQuery=String.format("select %s, %s from %s", strFieldName, strFieldName2, strTableName);
st=conn.createStatement();
rs=st.executeQuery(strSQLQuery);
//rest code
}
Below is the solution in java.
String strSelectString = String.format("select %s, %s from %s", strFieldName, strFieldName2, strTableName);

Categories