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.
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.
I am writing a database program. But I am stuck with the Java prepared statement. The prepared statement doesn't seems to be working. I spend several hours to make it work but still same result.
String sql = "INSERT into EDMSDATABASE.MESSAGE (title, subject, description, deadline) VALUES (?, ?, ?, ?)";
try (
PreparedStatement statement = connection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
) {
statement.setString(1, bean.getTitle());
statement.setString(2, bean.getSubject());
statement.setString(3, bean.getDescription());
statement.setString(4, bean.getDeadline());
int affectedRow = statement.executeUpdate();
if(affectedRow == 1) return "Success";
} catch (SQLException e)
{
} finally{
}
Note that bean is a parameter
Are you using 1.7 . If not please use version compatible logic.
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.
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();
I am trying to insert data a user enters into a jtextfield into an msaccess database. When I try to execute my sql statement I get an error stating Syntax error in INSERT INTO statement.
I checked my sql statement and tried a few different things but cannot seem to find any kind of syntax error.
conn = Connect.ConnectDB();
String sql = "insert into Team ("
+"TeamID,"
+"TeamCity,"
+"TeamMascot,"
+ "values("+txtid.getText()+ ",'"+txtname.getText()+"','"+txtaddress.getText()+"')" ;
try{
pst = conn.prepareStatement(sql);
pst.execute();
JOptionPane.showMessageDialog(null, "Entry " + txtid.getText() + " Saved");
UpdateJTable();
//conn.close();
}
catch(Exception e){
JOptionPane.showMessageDialog(null, e);
}
The error is the extra comma and no closing parenthesis before the keyword values
String sql = "insert into Team ("
+"TeamID,"
+"TeamCity,"
+"TeamMascot," // <<== HERE, change comma into closing parenthesis
By the way, your statement is vulnerable with SQL Injection. You can avoid it if you parameterized the values. Eg,
String sql = "insert into Team (TeamID,TeamCity,TeamMascot) values (?, ?, ?, ?)"
pst = conn.prepareStatement(sql);
pst.setString(1, txtid.getText());
pst.setString(2, txtname.getText());
pst.setString(3, txtaddress.getText());
PreparedStatement