In my database I have two tables called car and ad. In car i have a foreign key referencing the adId value in ad. When i run my code, i don't get any errors, but data is only inserted into ad, not car. Any suggestions? Here's my code:
public void createAd(Ad ad, Car car) {
try {
Class.forName("org.postgresql.Driver");
if (con != null) {
ps = con.prepareStatement("INSERT INTO \"ad\"(\"title\", \"description\", \"author\", \"image\") VALUES (?, ?, ?, ?)");
ps.setString(1, ad.getTitle());
ps.setString(2, ad.getDescription());
ps.setString(3, ad.getAuthor());
ps.setBytes(4, ad.getImage());
ps.executeQuery();
ps = con.prepareStatement("SELECT currval('\"ad_adId_seq\"');");
rs = ps.executeQuery();
rs.next();
int adId = rs.getInt("currval");
ps = con.prepareStatement("INSERT INTO \"ad\"(\"adId\") VALUES (?);");
ps.setInt(1, adId);
ps.executeUpdate();
ad.setAdId(adId);
ps = con.prepareStatement("INSERT INTO \"car\"(\"distanceTraveled\", \"age\", \"condition\", \"vin\", \"brand\", \"price\", \"ad_adId\") VALUES (?, ?, ?, ?, ?, ?, ?)");
ps.setInt(1, car.getDistanceTraveled());
ps.setInt(2, car.getAge());
ps.setString(3, car.getCondition());
ps.setString(4, car.getVIN());
ps.setString(5, car.getBrand());
ps.setInt(6, car.getPrice());
ps.setInt(6, adId);
ps.executeQuery();
car.setAdId(adId);
}
} catch (Exception ex) {
System.out.println(ex);
}
}
There is an error in your last query :
ps.setInt(7, adId);
instead of
ps.setInt(6, adId);
I suggest that you should take a look at spring-database. Using JdbcTemplate will reduce a lot of the JDBC boiler plate code and more important will take care for a lot of jdbc connection leaks worries for you.
If you sill need to use plain JDBC, you need to properly initialize the connection object and use update instead of query, when using update statements.
Also you need to properly close the statement objects that were created.
You should do something similar to the below code:
Connection con = null;
PrepareStatement ps1 = null;
PrepareStatement ps2 = null;
PrepareStatement ps3 = null;
PrepareStatement ps4 = null;
ResultSet rs = null;
String url = "jdbc:postgresql://localhost/dbName";
String user = "userName";
String password = "userPass";
try {
con = DriverManager.getConnection(url, user, password);
ps1 = con.prepareStatement("INSERT INTO \"ad\"(\"title\", \"description\", \"author\", \"image\") VALUES (?, ?, ?, ?)");
ps1.setString(1, ad.getTitle());
ps1.setString(2, ad.getDescription());
ps1.setString(3, ad.getAuthor());
ps1.setBytes(4, ad.getImage());
ps1.executeUpdate();
ps2 = con.prepareStatement("SELECT currval('\"ad_adId_seq\"');");
rs = ps2.executeQuery();
if(rs.next())
int adId = rs.getInt("currval");
}
ps3 = con.prepareStatement("INSERT INTO \"ad\"(\"adId\") VALUES (?);");
ps3.setInt(1, adId);
ps3.executeUpdate();
ad.setAdId(adId);
ps4 = con.prepareStatement("INSERT INTO \"car\"(\"distanceTraveled\", \"age\", \"condition\", \"vin\", \"brand\", \"price\", \"ad_adId\") VALUES (?, ?, ?, ?, ?, ?, ?)");
ps4.setInt(1, car.getDistanceTraveled());
ps4.setInt(2, car.getAge());
ps4.setString(3, car.getCondition());
ps4.setString(4, car.getVIN());
ps4.setString(5, car.getBrand());
ps4.setInt(6, car.getPrice());
ps4.setInt(7, adId);
ps4.executeUpdate();
car.setAdId(adId);
} catch (SQLException ex) {
Logger lgr = Logger.getLogger(getClass().getName());
lgr.log(Level.SEVERE, "Unable to execute updates", ex);
} finally {
try {
if (rs != null)
rs.close();
if (ps1 != null)
ps1.close();
if (ps2 != null)
ps2.close();
if (ps3 != null)
ps3.close();
if (ps4 != null)
ps4.close();
if (con != null)
con.close();
} catch (SQLException ex) {
Logger lgr = Logger.getLogger(getClass().getName());
lgr.log(Level.WARNING, "Unable to close the connection", ex);
}
}
Related
I am trying register page, if email exits already it should get alert message, for this below is my some part of the code, i am using executeQuery for Select query but still i am getting error:
java.sql.SQLException: Can not issue executeUpdate() or executeLargeUpdate() for SELECTs
java code:
Class.forName("com.mysql.jdbc.Driver");
Connection cn=DriverManager.getConnection("jdbc:mysql://localhost:3306/xxxx", "root","root");
PreparedStatement ps=cn.prepareStatement("select * from Register where email=?");
ps.setString(1, email);
ResultSet rs=ps.executeQuery();
if(rs.next())
{
out.println("<script type=\"text/javascript\">");
out.println("alert('Email already Exists Please Try with New Email');");
out.println("location='index.html';");
out.println("</script>");
}
else{
PreparedStatement ps1 = cn.prepareStatement("insert into Register values(?,?,?,?,?)");
ps1.setString(1, name);
ps1.setString(2, email);
ps1.setString(3, mobile);
ps1.setString(4, password);
ps1.setString(5, conform_password);
int i = ps.executeUpdate();
if (i != 0) {
response.sendRedirect("index.html");
} else {
out.println("Some Thing went wrong. Try Again...");
}
}
}
My guess is that the problem has to do with your not closing the first statement used for the select before you try to create another statement for the insert. But, there is a better way to implement your logic, using a single insert:
String sql = "INSERT INTO Register (name, email, mobile, password, confirm_password) ";
sql += "SELECT ?, ?, ?, ?, ? ";
sql += "WHERE NOT EXISTS (SELECT 1 FROM Register WHERE email = ?)";
PreparedStatement ps = cn.prepareStatement(sql);
ps.setString(1, name);
ps.setString(2, email);
ps.setString(3, mobile);
ps.setString(4, password);
ps.setString(5, conform_password);
ps.setString(6, email);
int i = ps.executeUpdate();
if (i == 0) {
System.out.println("Email already Exists Please Try with New Email");
}
else {
response.sendRedirect("index.html");
}
If the exists clause of the above insert fails, then nothing should be inserted, and the DML row count returned by executeUpdate() should be zero.
Im trying to create an application that allows users to create a profile however when im inserting into the DB I get the error shown above. I've had a look at similiar solutions but nothing seems to have worked.
The relevant code as it stands is;
//Invokes myConnection class to link to DB
Connection con = myConnection.getConnection();
PreparedStatement ps;
try
{
//Adds the selected text to DB
ps = con.prepareStatement("INSERT INTO `user`(`username`, `realname`, `password`, `email`, `gym`, `belt`, `dateofbirth`, `profilepic`, `biography`, `motto`) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
ps.setString(1, jTextFieldUsername.getText());
ps.setString(2, jTextFieldName.getText());
ps.setString(3, String.valueOf(jPasswordFieldPass.getPassword()));
ps.setString(4, jTextFieldEmail.getText());
ps.setString(5, jTextFieldGym.getText());
ps.setString(6, jComboBoxBelt.toString());
ps.setDate(7, convertUtilDateToSqlDate(jDateChooserDOB.getDate()));
InputStream img = new FileInputStream(new File(imagePath));
ps.setBlob(8, img);
if(ps.executeUpdate() != 0)
{
JOptionPane.showMessageDialog(null, "Account Created!");
}
else
{
JOptionPane.showMessageDialog(null, "Oops! Something went wrong!");
}
ps.setString(9, jTextAreaBiography.getText());
ps.setString(10, jTextAreaMotto.getText());
}
catch (Exception ex)
{
Logger.getLogger(RegisterPage.class.getName()).log(Level.SEVERE, null, ex);
}
Sorry if this is straight forward and thanks in advance for your help!
Edit: Answered simply, thanks was having a complete brainfart there.
The problem in your code is,
You have to set all the values for the parameters and then use execute statement.
your code should be like this.
ps = con.prepareStatement("INSERT INTO `user`(`username`, `realname`, `password`, `email`, `gym`, `belt`, `dateofbirth`, `profilepic`, `biography`, `motto`) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
ps.setString(1, jTextFieldUsername.getText());
ps.setString(2, jTextFieldName.getText());
ps.setString(3, String.valueOf(jPasswordFieldPass.getPassword()));
ps.setString(4, jTextFieldEmail.getText());
ps.setString(5, jTextFieldGym.getText());
ps.setString(6, jComboBoxBelt.toString());
ps.setDate(7, convertUtilDateToSqlDate(jDateChooserDOB.getDate()));
InputStream img = new FileInputStream(new File(imagePath));
ps.setBlob(8, img);
ps.setString(9, jTextAreaBiography.getText());
ps.setString(10, jTextAreaMotto.getText());
if(ps.executeUpdate() != 0)
{
JOptionPane.showMessageDialog(null, "Account Created!");
}
else
{
JOptionPane.showMessageDialog(null, "Oops! Something went wrong!");
}
You are running ps.executeUpdate() without setting parameters 9 and 10.
Move these lines before if(ps.executeUpdate() != 0):-
ps.setString(9, jTextAreaBiography.getText());
ps.setString(10, jTextAreaMotto.getText());
I have been trying to add values to a table named bill_items and this is the coding for the button "add to cart" but it shows and error saying "Unknown column Jacket in field list. What is wrong in this coding?
try {
rs = stmt.executeQuery("select * from mens_wear where Item_code = 1090;");
while(rs.next()){
icode = rs.getInt("Item_code");
p = rs.getInt("Price");
bname = rs.getString("Brand_Name");
iname = rs.getString("Item_Name");
t = rs.getString("Type");
}
rs.close();
stmt.close();
con.close();
} catch(Exception e)
{JOptionPane.showMessageDialog(null,e.getMessage());}
try {
Class.forName("java.sql.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost/aashita","root","1510");
stmt = con.createStatement();
int a = stmt.executeUpdate("insert into bill_items values('"+icode+"','"+t+"','"+bname+"','"+iname+"','"+p+"');");
JOptionPane.showMessageDialog(null,"Added Successfully");
} catch(Exception e) {
JOptionPane.showMessageDialog(null,e.getMessage());
}
}
It is a bad practice to not specify column names in an insert and depend on table column order. There could also be an issue with escaping of your query string if any of your values contain quotes. I would try adding the column names and using a prepared statement with parameters.
string updateText = "insert into bill_items (Item_code, Type, Brand_Name, Item_Name, Price) ";
updateText += "values (?, ?, ?, ?, ?)";
PreparedStatement stmt = con.prepareStatement(updateText);
stmt.setInt(1, icode);
stmt.setString(2, t);
stmt.setString(3, bname);
stmt.setString(4, iname);
stmt.setInt(5, p);
int a = stmt.executeUpdate();
sorry if my questions are identical. I was trying to find out online documentation but I still have not solved the problem. it's an error in the line "stmt.executeUpdate ();"
public class DBConnect {
private List<SinhVien> result = new ArrayList<SinhVien>();
public void updateSQL(String masv, String malop, String ten,
Date ngaysinh, String diachi) {
try{
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Connection connection = DriverManager.getConnection("jdbc:sqlserver://MyPC:1433;databasename=QLSV;username=sa;password=APASSWORD");
PreparedStatement stmt = connection.prepareStatement("INSERT INTO SinhVien(masv, malop, ten, ngaysinh, diachi) VALUES(?, ?, ?, ?, ?");
stmt.setString(1, masv);
stmt.setString(2, malop);
stmt.setString(3, ten);
stmt.setDate(4, ngaysinh);
stmt.setString(5, diachi);
stmt.executeUpdate();
}
catch(Exception e){
e.printStackTrace();
}
}
public static void main(String[] args) {
DBConnect dbConnect = new DBConnect();
dbConnect.XuatDSSV();
dbConnect.findSinhvienById("51003146");
dbConnect.updateSQL("123", "malop", "ten", null, "diachi");
}
I suggest you store your query in a String. It would have been easier to read, and find the problem...
final String query = "INSERT INTO SinhVien"
+ "(masv, malop, ten, ngaysinh, diachi) "
+ "VALUES(?, ?, ?, ?, ?)"; // <-- You were missing the close paren.
PreparedStatement stmt = connection.prepareStatement(query);
Try to add connection.commit() after stmt.executeUpdate(). And please, post the exception.
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.