Insert declared variables into db Table using Java - java

So I am having a slight problem inserting values into a table I created in netbeans. I will show you the code that works and creates a new worker in the table and then show you what goes wrong when I try to change it.
This is a method from a class called dbConnect.java
public void insertTableRow() {
try {
Connection con = DriverManager.getConnection(host, uName, uPass);
Statement stmt = con.createStatement();
String SQL = "INSERT INTO Workers VALUES (10, 'John', 'Smith', 'Engineer')";
stmt.executeUpdate(SQL);
} catch (SQLException err) {
System.out.println(err.getMessage());
}
}
And is here where I call it in the main class.
dbConnect test = new dbConnect();
test.insertTableRow();
And then I get a John Smith appears so I know I have the right code. BUT when I try to enter in variables into VALUES it all falls apart. i.e.
public void insertTableRow(int id, String firstName, String lastName, String jobTitle) {
try {
int num = id;
String fName = firstName;
String lName = lastName;
String jTitle = jobTitle;
Connection con = DriverManager.getConnection(host, uName, uPass);
Statement stmt = con.createStatement();
String SQL = "INSERT INTO Workers VALUES (num, fName, lName, jTitle)";
stmt.executeUpdate(SQL);
} catch (SQLException err) {
System.out.println(err.getMessage());
}
}
Combined with -
dbConnect test = new dbConnect();
test.insertTableRow(10, "John", "Smith", "Doctor");
System.out.println(test.getTableContents());
The error I get back is:- Column 'NUM' is either not in any table in the FROM list or appears within a join specification and is outside the scope of the join specification or appears in a HAVING clause and is not in the GROUP BY list. If this is a CREATE or ALTER TABLE statement then 'NUM' is not a column in the target table.
So what am doing wrong because I have absolutely no idea?

when I try to enter in variables into VALUES it all falls apart
Statement stmt = con.createStatement();
String SQL = "INSERT INTO Workers VALUES (num, fName, lName, jTitle)";
stmt.executeUpdate(SQL);
You're not sending any variables. You have num, fName and the other variables but you're sending them as plain text in your SQL statement. You need to pass the values of your variables into your SQL statement.
The best approach to do this is using PreparedStatement:
String SQL = "INSERT INTO Workers VALUES (?, ?, ?, ?)";
PreparedStatement pstmt = con.prepareStatement(SQL);
p.setInt(1, num);
p.setString(2, fName);
p.setString(3, lName);
p.setString(4, jTitle);
pstmt.executeUpdate();
pstmt.close();
You may also use the naive approach of concatenating the values of each variable in your SQL statement, but it is unsafe and allows SQL Injection attacks. So the best bet is to use PreparedStatement.
More info:
Difference between Statement and PreparedStatement

Related

SQL insert into Quotes wrong

int rs = stmt.executeUpdate("INSERT INTO Leden VALUES (null,"+u+","+p+",'1')");
I'm getting the error
java.sql.SQLException: Unknown column '(the U variable)' in 'field list';
I know for sure it is 100% the "" but i can't seem to find it where it goes wrong
any help is appreciated!
This is my whole method (I want to learn how to do it with a prepared statement)
public static void connectionDB(String u, String p, String f){
{
try {
String username = "/////////";
String password = "///////";
String url = "///////////////";
Connection connection = DriverManager.getConnection(url, username, password);
Statement stmt = connection.createStatement();
int rs = stmt.executeUpdate("INSERT INTO Leden VALUES (null,'"+u+"','"+p+"','1')");
} catch (SQLException e) {
e.printStackTrace();
}
System.out.println("Database connected!");
}
}
It should be like
int rs = stmt.executeUpdate("INSERT INTO Leden VALUES (null,'"+u+"','"+p+"','1')");
Update:-
You can also look into prepared statements because
Prepared statements are much faster when you have to run the same statement multiple times, with different data. Thats because SQL will validate the query only once, whereas if you just use a statement it will validate the query each time.
Assuming fields are A,B,C,D;
A is int and remains are strings
String insertTableSQL = "INSERT INTO Leden"
+ "(A,B,C,D) VALUES"
+ "(?,?,?,?)";
preparedStatement.setInt(1, 11);
preparedStatement.setString(2, "Hello");
preparedStatement.setString(3, "this");
preparedStatement.setString(4, "OP");]
preparedStatement .executeUpdate();
It should be
int rs = stmt.executeUpdate("INSERT INTO Leden VALUES (null,'"+u+"','"+p+"','1')'");
The issue is, that " is used in SQL for objects like columns or tables, whereas ' is used for strings. So in +u+, which seems to not exists in context of your query.
Your query itself should therefore look something like (given, that +u+ and +p+ are strings.
INSERT INTO Leden VALUES (null,'+u+','+p+','1')
If you need to have " inside your columns, it would read like
INSERT INTO Leden VALUES (null,'"+u+"','"+p+"','1')
Also I would recommend to specify the columns you are inserting to so it looks similar to:
INSERT INTO "Leden" ("col1", "col2", "col3", "col4") VALUES (null,'+u+','+p+','1')
This will prevent your query from failing when extending table definition by another column.
Also using prepared statements could be a good idea here, as it helps you preventing from e.g. SQL injections.

Reading data from mysql database using java

Firstly, I'm reading the product name and number of products from user using jTextFields. For that product I read the product id and price from database using sql query. But in the below code I display the product price in a jtextField but while running tha file I get query executed successfully but I'm not getting anything in the jtextField.
And please check the sql query and resultset use,
table name is "item" and database name is "myshop",
I declared variables globelly and this code is in a jButton's 'ActionPeformed" part.
String item_name=name.getText();
int item_no=Integer.parseInt(no.getText());
String sql="SELECT id,price FROM item WHERE item.name='item_name'";
try{
Class.forName("com.mysql.jdbc.Driver");
Connection con(Connection)DriverManager.getConnection("jdbc:mysql://localhost:3306/myshop","root","mysql");
java.sql.Statement stmt=con.createStatement();
if (stmt.execute(sql)) {
rs = stmt.getResultSet();
JOptionPane.showMessageDialog(this, "succes","executed query",JOptionPane.PLAIN_MESSAGE);
} else {
System.err.println("select failed");}
int idIndex = rs.findColumn("id");
int priceIndex = rs.findColumn("price");
while(rs.next()){
item_id=rs.getInt(idIndex);
item_price=rs.getInt(priceIndex);
jTextField1.setText(""+item_price);//displaying product price in a jTextField1
jTextField2.setText(""+item_id);//displaying product id in a jTextField2
}
}
catch(Exception e){
JOptionPane.showMessageDialog(this, e.getMessage());
}
This line should be
String sql="SELECT id,price FROM item WHERE item.name='item_name'";
like this
String sql="SELECT id,price FROM item WHERE item.name='"+item_name+"'";
Use a PreparedStatement so you don't have to worry about delimiting all the variables:
String sql="SELECT id, price FROM item WHERE item.name = ?";
PreparedStatement stmt = connection.prepareStatement(sql);
stmt.setString( 1, item_name);
ResultSet rs = stmt.executeQuery();
Then the prepared statement will replace the variable for you with the proper quotes.
you would need to take item_name as param and put in quotes,
String sql="SELECT id,price FROM item WHERE item.name='"+ item_name+"'";
Try to avoid this type of mistake by using PreparedStatement
String sql="SELECT id,price FROM item WHERE item.name=?";
PreapredStatement ps = con.prepareStatement(sql);
ps.setString(1,item_name);
ResultSet rs = ps.executeQuery();
Use of PreparedStatement also prevent SQL injection attack.
try this code .
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/myshop","root","mysql");
PreparedStatement pt=con.prepareStatement("SELECT id,price FROM item WHERE item.name=?");
pt.setString(1,"item_name");
ResultSet rs;
if(pt.execute())
{
rs=pt.getResultSet();
JOptionPane.showMessageDialog(this, "succes","executed query",JOptionPane.PLAIN_MESSAGE);
}
else {
System.err.println("select failed");
}
while(rs.next()){
item_id=rs.getInt(1);
item_price=rs.getInt(2);
jTextField1.setText(""+item_price);//displaying product price in a jTextField1
jTextField2.setText(""+item_id);//displaying product id in a jTextField2
}
First, you need an reader, like this
private static void reader() throws SQLException {
DataBaseName db = new DataBaseName ();
names = db.getNames();
}

What am I doing wrong in inserting data to mysql table?

After executing code I get the Data saved message but no data is recorded in my clients table? I'm new to databases with Java, What am I doing wrong or how can I fix my code?
String sqlUrl = "jdbc:mysql://localhost:3306/clientinformation";
String user = "root";
String pass = "root";
String name = firstName.getText();
String lname = lastName.getText();
String cEmail = email.getText();
String rate = rateDbl.getText();
String cUrl = url.getText();
try {
Connection con = DriverManager.getConnection(sqlUrl, user, pass);
PreparedStatement st = con.prepareStatement("insert into clients
values('"+name+"', '"+lname+"', "
+ "'"+cEmail+"', '"+rate+"', '"+cUrl+"')");
JOptionPane.showMessageDialog(null, "Data saved!");
} catch (SQLException ex) {
Logger.getLogger(newClient.class.getName()).log(Level.SEVERE, null, ex);
}
What am I doing wrong
Well, you're building your SQL statement by concatenating values. That leads to SQL injection attacks - amongst other issues. Fortunately, that hasn't actually created a problem just yet - because you're never executing your statement.
You need to:
Parameterize your SQL, to avoid a SQL injection attack - use question marks for the parameters, and then use st.setString to set each parameter:
Connection con = DriverManager.getConnection(sqlUrl, user, pass);
PreparedStatement st = con.prepareStatement(
"insert into clients values (?, ?, ?, ?, ?)");
st.setString(1, name);
st.setString(2, lname);
st.setString(3, cEmail);
st.setString(4, rate); // Should this really be a string?
st.setString(5, cUrl);
st.executeUpdate();
JOptionPane.showMessageDialog(null, "Data saved!");
Call st.executeUpdate before you display the dialog box. (Ideally you shouldn't be mixing UI and data access in the same method, but...)
Please make the changes in that order though - do not just add a call to st.executeUpdate, or you've got a horrible security hole in your app.
The reason you're not seeing the data is you prepare the statement but never execute it. Call st.execute(); or st.executeUpdate(); to execute it.
Separately, though: That code is subject to SQL injection (attacks or otherwise); fun illustration here. Half the point of prepared statements is to protect against them. Use the parameters that prepared statements give you:
PreparedStatement st = con.prepareStatement("insert into clients values(?, ?, ?, ?, ?)");
int n = 1;
st.setString(n++, name);
st.setString(n++, lname);
st.setString(n++, cEmail);
st.setString(n++, rate);
st.setString(n++, cUrl);
// And then the missing execute
st.execute();

insert skips last record in recordset

I am writing a program that pulls data out of one schema, restructures the data to fit a new schema, and then inserts the data into a new database with the new schema. The problem is that, in my test code, the last record is not being inserted into the new database.
I am enclosing a greatly simplified version of the code below, which nonetheless recreates the problem. Can anyone show me how to fix the below so that all records in the recordset are inserted into the destination database? Currently, the below does correctly print out the last record in system.out.println, but yet that last record is not present in the destination table afterwards:
static void migrateDataTest(){
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection sourceConn = DriverManager.getConnection("jdbc:odbc:source_data_test");
Statement st = sourceConn.createStatement();
Connection destinationConn = DriverManager.getConnection("jdbc:odbc:receive_data_test");
int ClientNumber; String ClientsLastName; String ClientsFirstName;
ResultSet rest = st.executeQuery("SELECT ClientNumber, ClientsLastName, ClientsFirstName FROM sourceTable");
PreparedStatement ps5 = null;
while(rest.next()){
ClientNumber = rest.getInt(1);
ClientsLastName = rest.getString(2);
ClientsFirstName = rest.getString(3);
System.out.println(ClientNumber+", "+ClientsLastName+", "+ClientsFirstName);
ps5 = destinationConn.prepareStatement(
"INSERT INTO destinationTable ("
+ "ClientNumber, FirstName, LastName) VALUES (?, ?, ?)"
);
ps5.setInt(1, ClientNumber);
ps5.setString(2, ClientsFirstName);
ps5.setString(3, ClientsLastName);
ps5.executeUpdate();
destinationConn.commit();
}
ps5.close();
}
catch (ClassNotFoundException cnfe){cnfe.printStackTrace();}
catch (SQLException e) {e.printStackTrace();}
}
EDIT:
As per Lokesh's request, I am putting the entire code block which creates this error below. I just ran it again to confirm that it is printing record 30 in system.out.println, but that the destination table does not contain record number 30. The fact that the skipped record is printing out with system.out.println causes me to believe that the code below contains the error:
static void migrateDataTest(){
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection sourceConn = DriverManager.getConnection("jdbc:odbc:source_test");
Statement st = sourceConn.createStatement();
Connection destinationConn = DriverManager.getConnection("jdbc:odbc:receive_data_test");
int ClientNumber;
String ClientsLastName;
String ClientsFirstName;
String ClientsMiddleInitial;
Date DOB;
int GenderNumber;
int RaceNumber;
ResultSet rest = st.executeQuery("SELECT ClientNumber, ClientsLastName, ClientsFirstName, ClientsMiddleInitial, DOB, GenderNumber, RaceNumber FROM sourceTable");
PreparedStatement ps5 = null;
while(rest.next()){
ClientNumber = rest.getInt(1);
ClientsLastName = rest.getString(2);
ClientsFirstName = rest.getString(3);
ClientsMiddleInitial = rest.getString(4);
DOB = rest.getDate(5);
GenderNumber = rest.getInt(6);
RaceNumber = rest.getInt(7);
System.out.println(ClientNumber+", "+ClientsLastName+", "+ClientsFirstName+", "+ClientsMiddleInitial+", "+DOB+", "+GenderNumber+", "+RaceNumber);
ps5 = destinationConn.prepareStatement(
"INSERT INTO destinationTable ("
+ "ClientNumber, FirstName, MiddleInitial, LastName, DOB, GenderNumber, RaceNumber) "
+"VALUES (?, ?, ?, ?, ?, ?, ?)"
);
ps5.setInt(1, ClientNumber);
ps5.setString(2, ClientsFirstName);
ps5.setString(3, ClientsMiddleInitial);
ps5.setString(4, ClientsLastName);
ps5.setDate(5, DOB);
ps5.setInt(6, GenderNumber);
ps5.setInt(7, RaceNumber);
ps5.executeUpdate();
destinationConn.commit();
}
ps5.close();
}
catch (ClassNotFoundException cnfe){cnfe.printStackTrace();}
catch (SQLException e) {e.printStackTrace();}
}
The solution, oddly enough, was to create and execute an additional prepared statement after the one that was failing to insert the final value in its recordset. Once I added an additional prepared statement afterwards, the first one began to consistently insert all of its values.
Seems like some nuance in java code that perhaps is missing in the code samples that I posted in my original posting above.

Inserting variable values into SQL Server using Java

So far I have been able to insert data into my SQL table only when i declare values inside the executedUpdate statement. What I wanted to know if there is a way that I can pass those values as variables that I will declare as parameters in the executing method like so:
public void updateSQL(String name, String dnsName, String ipV4, String ipV6, int statusCode)
{
try
{
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Connection connection = DriverManager.getConnection("jdbc:sqlserver://servername;database=databasename;integratedSecurity=true");
System.out.println("Database Name: " + connection.getMetaData().getDatabaseProductName());
Statement statement = connection.createStatement();
statement.executeUpdate("INSERT INTO ComputerStatus(Name, DNSName, IPAddressV4, IPAddressV6, StatusCodeID)" + "VALUES(#Name, #DNSName, #IPAddressV4, #IPAddressV6, #StatusCodeID)");
System.out.println("Data Inserted");
ResultSet resultSet = statement.executeQuery("SELECT Name FROM ComputerStatus");
while(resultSet.next())
{
System.out.println("Computer Name: " + resultSet.getString("Name"));
}
connection.close();
}
catch (Exception e)
{
e.printStackTrace();
System.err.println("Problem Connecting!");
}
}
I've tried couple of different things but no luck so far. Anyone know if this can be done?
You may use PreparedStatement instead of Statement.
PreparedStatement stmt = connection.prepareStatement("insert into test (firstname, lastname) values (?, ?");
stmt.setString(1, name);
stmt.setString(2, lname);
stmt.executeUpdate();
Using this way, you prevent SQL injection.
Have a look here :
PreparedStatement prep = conn.prepareStatement("INSERT INTO ComputerStatus(Name, DNSName, IPAddressV4, IPAddressV6, StatusCodeID) VALUES(?, ?, ?, ?, ?)");
prep.setString(1, name);
prep.setString(2, dnsName);
prep.setString(3, ipV4name);
prep.setString(4, ipV6);
prep.setInt(5, statusCode);
prep.executeUpdate();
this will help you understand.

Categories