INSERT INTO statement in java servlet.

Hiya

Was wondering if anyone knew how to use variables from an html form into a sql insert into statement? The constants work ok below, its just getting the variables to work.

//constants work ok.

rs = stmt.executeQuery("INSERT INTO ACCOUNTS " + " VALUES ('un', 'test2', 'test2', 'test2', 'test', 'test', 'test', 'test', 'test')");

//doesn't do anything no errors.

rs = stmt.executeQuery("INSERT INTO ACCOUNTS " + " VALUES ( '"+uname+"'," + "'"+fname+"'," + "'"+sname+"'," + "'"+address1+"'," + "'"+address2+"'," + "'"+town+"'," + "'"+county+"'," + "'"+postcode+"')");

[644 byte] By [Emmaqa] at [2007-11-26 19:04:43]
# 1

> Hiya

>

> Was wondering if anyone knew how to use variables

> from an html form into a sql insert into statement?

> The constants work ok below, its just getting the

> variables to work.

>

Maybe I am missing something, what does html have to do with it?

>

> //constants work ok.

> rs = stmt.executeQuery("INSERT INTO ACCOUNTS " + "

> VALUES ('un', 'test2', 'test2', 'test2', 'test',

> 'test', 'test', 'test', 'test')");

>

> //doesn't do anything no errors.

>

You should be using a PreparedStatement for this.

> rs = stmt.executeQuery("INSERT INTO ACCOUNTS " + "

> VALUES ( '"+uname+"'," + "'"+fname+"',"

> + "'"+sname+"'," + "'"+address1+"'," +

> "'"+address2+"'," + "'"+town+"'," + "'"+county+"',"

>+ "'"+postcode+"')");

So doesn't do anything means no rows inserted?

zadoka at 2007-7-9 20:53:46 > top of Java-index,Database Connectivity,Java Database Connectivity (JDBC)...
# 2

Hello,

First u have to fill the test fields and submit the Form.

We have to get all the values from the html page using following st and store the values:

String temp1 = request.getParameter(Emp_Name);

Now u can use insert statement and pass these strings

stmt.executeQuery("INSERT INTO Table VALUES ('temp1', 't2' );

Rajendera at 2007-7-9 20:53:46 > top of Java-index,Database Connectivity,Java Database Connectivity (JDBC)...
# 3

Hi,

Yes I have tried using a prepared statement but anyway I think the syntax for the variable code is wrong.

The html form lists and gains the variables from the user when entering in data from the html form which then gets used in the servlet by request parameter.

I just need to know the right syntax of using the variables within an INSERT INTO statement. Thanks.

Emmaqa at 2007-7-9 20:53:46 > top of Java-index,Database Connectivity,Java Database Connectivity (JDBC)...
# 4
You uses stmt.executeUpdate("INSERT yada INTO blah"); Update for insert and delete and so on Query for searchers and so forth, think u get the idea
Rudigera at 2007-7-9 20:53:46 > top of Java-index,Database Connectivity,Java Database Connectivity (JDBC)...
# 5

> I just need to know the right syntax of using the

> variables within an INSERT INTO statement. Thanks.

PreparedStatement ps =

conn.prepareStatement("INSERT INTO ACCOUNTS VALUES (?,?,?,?,?,?,?,?)");

ps.setString(1, uname);

ps.setString(2, sname);

// and so on

Much better than the rat's nest of quotes you had before. Anyway was that what you meant by "syntax of using the variables"? It's pretty straightforward. If you are having trouble getting data into those variables, that's not a JDBC question.

DrClapa at 2007-7-9 20:53:46 > top of Java-index,Database Connectivity,Java Database Connectivity (JDBC)...
# 6

um actually, I'm not having problems getting data into those variables because those variables work with test code I did in system.out.println. Anyway, that code does not work for some reason, although I have trailed many websites that say almost the same code, some use + variable name + etc and some use your preparedstatement, and that is exactly how i've done it so something is amiss. And it is a JDBC question as such, related, since it is importing data into a database. The constant test string works fine btw and I know the variables are getting the right data from the HTML Form, as I mentioned above.

Regards.

Emmaqa at 2007-7-9 20:53:46 > top of Java-index,Database Connectivity,Java Database Connectivity (JDBC)...
# 7

Okay. Then you're going to have to say something more specific than "how do I get variables to work". Because "getting variables to work" is just a general Java concept. We need a clearer picture of your problem.

I assume you aren't getting any errors, because you didn't mention any. Or is that a bad assumption?

DrClapa at 2007-7-9 20:53:46 > top of Java-index,Database Connectivity,Java Database Connectivity (JDBC)...
# 8
Wow you actually tried to answer someones request!! I was beginning to wonder.
rplaisancea at 2007-7-9 20:53:46 > top of Java-index,Database Connectivity,Java Database Connectivity (JDBC)...
# 9

<html>

<head>

<title>

CreateAccount

</title>

</head>

<body>

<form method=get action=/servlet/website.CreateAccount>

Username:

<input type=text name="username">

Password:

<input type=text name="password">

First Name:

<input type=text name="firstname">

Surname:

<input type=text name="surname">

1st Line of Address:

<input type=text name="1address">

2nd Line of Address:

<input type=text name="2address">

Town:

<input type=text name="town">

County:

<input type=text name="county">

Postcode:

<input type=text name="postcode">

<input type=submit>

</form>

</body>

</html>

package website;

import java.io.*;

import java.sql.*;

import javax.servlet.*;

import javax.servlet.http.*;

public class CreateAccount extends HttpServlet {

private static final String CONTENT_TYPE = "text/html";

/**Initialize global variables*/

public void init(ServletConfig config) throws ServletException {

super.init(config);

}

/**Process the HTTP Get request*/

public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {

ResultSet rs = null;

Connection con = null;

res.setContentType("text/html");

PrintWriter out = res.getWriter();

//get the variables entered in the form

String uname = req.getParameter("username");

String pwd = req.getParameter("password");

String fname = req.getParameter("firstname");

String sname = req.getParameter("surname");

String address1 = req.getParameter("1address");

String address2 = req.getParameter("2address");

String town = req.getParameter("town");

String county = req.getParameter("county");

String postcode = req.getParameter("postcode");

try {

// Load the database driver

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

// Get a Connection to the database

con = DriverManager.getConnection("jdbc:odbc:account", "", "");

//Add the data into the database

try

{

String sql = "INSERT INTO ACCOUNTS " + " VALUES (?,?,?,?,?,?,?,?)";

PreparedStatement statement = con.prepareStatement(sql);

statement.setString(1, uname);

statement.setString(2, fname);

statement.setString(3, sname);

statement.setString(4, address1);

statement.setString(5, address2);

statement.setString(6, town);

statement.setString(7, county);

statement.setString(8, postcode);

int numRowsChanged = statement.executeUpdate(sql);

statement.close();

//Statement stmt = null;

//stmt = con.createStatement();

//Create a Statement object

//constants work ok.

//rs = stmt.executeQuery("INSERT INTO ACCOUNTS " + " VALUES ('uname', 'test2', 'test2', 'test2', 'test', 'test', 'test', 'test', 'test')");

}

catch (Exception e)

{

}

// show that the new account has been created

out.println("

New account created:

");

out.println(" '"+uname+"'");

}

catch(ClassNotFoundException e) {

out.println("Couldn't load database driver: " + e.getMessage());

}

catch(SQLException e) {

out.println("SQLException caught: " + e.getMessage());

}

finally {

// Always close the database connection.

try {

if (con != null) con.close();

}

catch (SQLException ignored) { }

}

}

}

ok now the regular statement with constant values inserts data into the database (the regular statement is being used with a result set )but the prepared statement does not - there are no error messages but it does not insert any data either. The data is going into the variables due to the system.out.println, but is it going into the prepared statement? I believe the prepared statement is being executed with the executeupdate method.

Emmaqa at 2007-7-9 20:53:46 > top of Java-index,Database Connectivity,Java Database Connectivity (JDBC)...
# 10

You believe that the PreparedStatement is being executed, but what if it is throwing an exception instead? Then this code is executed:catch (Exception e)

{

}

So if an exception happens, your code catches it and completely ignores it. If I were you I wouldn't have nested try-catch blocks, I would put all the JDBC code in a single try-catch. And don't swallow exceptions like that.

As far as I can see your code is otherwise okay, except I don't know what will happen if one of the variables from the form is null. Which would happen if the user left the field blank. I would think it should just put null into the database, but perhaps not. You're closing the connection correctly, so that suggests that an exception of some kind is happening.

DrClapa at 2007-7-9 20:53:46 > top of Java-index,Database Connectivity,Java Database Connectivity (JDBC)...
# 11

Hiya

Yes you were right about the exception clause, that basically gave no information whatsoever, it is a driver problem, the driver does not support it so therefore I will now have to test this probably on something like sql server with creating a new table within it and using the appropriate driver for it. There was infact, nothing wrong with the code itself.

Emmaqa at 2007-7-9 20:53:46 > top of Java-index,Database Connectivity,Java Database Connectivity (JDBC)...