Sql Command To Delete Values Taken From Text Fields [duplicate] - java

This question already has an answer here:
SQL Command To Delete Entry In Current Textfields For Java App
(1 answer)
Closed 9 years ago.
I use this command to insert a new client, I have a method in Java where I assign the values to the command:
insertNewPerson = connection.prepareStatement(
"INSERT INTO Addresses " +
"(FirstName, LastName, Email, PhoneNumber, ClientAddress ) " +
"VALUES (?, ?, ?, ?, ?)" );
Question: I am looking for something similar but for DELETING whatever entries are in the text fields of the program.
Here is the Java method I use to set the values in the sql command:
public int addPerson(
String fname, String lname, String email, String num, String caddress)
{
int result = 0;
//set parameters, then execute insertNewPerson
try {
insertNewPerson.setString(1, fname);
insertNewPerson.setString(2, lname);
insertNewPerson.setString(3, email);
insertNewPerson.setString(4, num);
insertNewPerson.setString(5, caddress);
//insert the new entry; return # of rows updated
result = insertNewPerson.executeUpdate();
}//end try
catch(SQLException sqlException) {
sqlException.printStackTrace();
close();
}//end catch
return result;
}//end method addPerson

From what I understand, you are looking for the DELETE SQL Command:
delete from Addresses
where FirstName = ?
and LastName = ?
and Email = ?
and PhoneNumber = ?
and ClientAddress = ?
This also takes into consideration your need to delete based on the values on the fields.

You should have a unique value for all records. If you have a primary key you can use this block.
deletePerson = connection.prepareStatement(
"DELETE FROM Addresses " +
"WHERE personID = ?" );

Related

cannot set null to a unique column

so this is my table
CREATE TABLE "client" (
"id" INTEGER,
"name" TEXT COLLATE NOCASE,
"surname" TEXT COLLATE NOCASE,
"number" TEXT UNIQUE COLLATE NOCASE,
"car_brand" TEXT,
"modele" TEXT,
"phone_nbr" TEXT,
PRIMARY KEY("id" AUTOINCREMENT));
when im adding a new statment from my java application i can add only one time NULL to the column number but i can add many nulls from the db browser
this is the code that i use
String number = tf_number.getText();
if(tf_number.getText().trim().isEmpty())
number = null;
String name = tf_name.getText();
String surname = tf_surname.getText();
String phoneNbr = tf_phoneNbr.getText();
String car_brand = tf_brand.getText();
String modele = tf_modele.getText();
Client c = new Client(name, surname, number, car_brand, modele, phoneNbr);
ClientCRUD pcd = new ClientCRUD();
pcd.addClient(p);
and this is the sql error
[SQLITE_CONSTRAINT_UNIQUE] A UNIQUE constraint failed (UNIQUE constraint failed: client.number)
this is the addClient() fonction
public void addClient(Client t) {
try {
String requete = "INSERT INTO CLIENT(name,surname,number,car_brand,MODELE,phone_nbr)"
+ "VALUES ('"+t.getClientName()+"','"+t.getClientSurname()+"','"+t.getNumber()+"',"
+ "'"+t.getCarBrand()+"','"+t.getModele()+"','"+t.getPhone()+"')";
Statement st = MyConnection.getInstance().getCnx()
.createStatement();
st.executeUpdate(requete);
System.out.println("Client added");
} catch (SQLException ex) {
System.out.println(ex.getMessage());
}
}
any solution ?
public void save(Person person) {
String query = "INSERT INTO person_info (" +
" name_p, " +
" age, " +
" address, " +
" email " +
")" +
"VALUES(?, ?, ?, ?)";
try(Connection connection = dbConnection.getConnection()) {
PreparedStatement prepStatement = connection.prepareStatement(query);
prepStatement.setString(1, person.getName());
prepStatement.setInt(2, person.getAge());
prepStatement.setString(3, person.getAddress());
prepStatement.setString(4, null);
prepStatement.execute();
}
catch (SQLException e){
e.printStackTrace();
}
}
##This will solve your problem
You code inserts the string "null" and not a real null like your browser do.
So there can be only 1 string with value "null" in that unique column.
You can use preparedStatement with parameters instead of the statement you use.
E.g:
PreparedStatement preparedStatement = connection.prepareStatement(sql))
This answers how to insert null using prepared statement: Insert null using prepared statement
And your sql string for the query should have the parameters.
See more about prepared statements: Prepared Statements Tutorial

Parameter index out of range (1 > number of parameters, which is 0). output when attempting to save information to database

I created a small program where the user must input data into text fields and select options from combo boxes. I created a database using XAMPP and created the corresponding tables for the program through the web browser.
The database is called activitydb and the table that's responsible for storing the data from the program is called userdata.
The first column in the table is called UserID and is an int that auto increments every time a new entry is added.
The rest are all varchars with varying maximum lengths.
This is currently the source code of the program:
Connection con = null;
Statement st = null;
try {
// activitydb = database name
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/activitydb?zeroDateTimeBehavior=convertToNull", "root", "");
st = con.createStatement();
// userdata = table name
String sqlconn = "INSERT INTO userdata (UserID, LastName, FirstName, MiddleName, Email, Sex, HomeAddress, City, CPUBrand, ComputerType, HardwareSpecs, GPUBrand, GPUType, GPUVRAM)";
PreparedStatement prdStmt = con.prepareStatement(sqlconn);
// Input of variable data into corresponding database table
// First table will be declared as null as it is an Integer designed with an Auto Increment
prdStmt.setString(1, null);
prdStmt.setString(2, jTextLastName.getText());
prdStmt.setString(3, jTextFirstName.getText());
prdStmt.setString(4, jTextMiddleName.getText());
prdStmt.setString(5, jTextEmail.getText());
prdStmt.setString(6, jComboBoxSex.getSelectedItem().toString());
prdStmt.setString(7, jTextHomeAddress.getText());
prdStmt.setString(8, jTextCity.getText());
prdStmt.setString(9, jComboBoxCPUBrand.getSelectedItem().toString());
prdStmt.setString(10, jComboBoxComputerType.getSelectedItem().toString());
prdStmt.setString(11, jComboBoxHardwareSpecs.getSelectedItem().toString());
prdStmt.setString(12, jComboBoxGPUBrand.getSelectedItem().toString());
prdStmt.setString(13, jComboBoxGPUType.getSelectedItem().toString());
prdStmt.setString(14, jComboBoxGPUVRAM.getSelectedItem().toString());
// Do this if something goes wrong
} catch (SQLException err) {
// Print error message to console for diagnosis
System.out.println(err.getMessage());
}
For the combo boxes, I've used getSelectedItem().toString() to have the data found inside stored as a String.
Clicking the button will make the program do nothing but print this in the console:
Parameter index out of range (1 > number of parameters, which is 0).
You are missing the place holders ? to put the values, your query should be :
String sqlconn = "INSERT INTO userdata (UserID, LastName, FirstName, MiddleName," +
" Email, Sex, HomeAddress, City, CPUBrand, ComputerType, HardwareSpecs," +
" GPUBrand, GPUType, GPUVRAM) " +
"VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";

Java Prepared Statement Cannot Update Database

I am using the prepared statement to store some variables into the database. The program runs without any errors but the database wont update.
public void setData(Dealer sDealer)
{
String fName = sDealer.getFirstName();
String lName = sDealer.getLastName();
int age = sDealer.getAge();
int xp = sDealer.getExperience();
String mStatus = sDealer.getMartialStatus();
String dAdd = sDealer.getAddress();
String pNum = sDealer.getPhoneNumber();
String email = sDealer.getEmailAddress();
String crime = sDealer.getCriminalRecord();
String type = sDealer.getCategory();
String SQL ="INSERT INTO DEALERS ("
+"firstName, " +"lastName ," +"dAge, "
+"dXp, " +"maritalStatus , " +"dAddress, "
+"phoneNumber, " +"dMail, " +"criminalRecord, " +"dType )"
+"VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
try{
My suspicion is on the following prepared statement I used in this method but I am unable to figure out just what I am doing wrong.
PreparedStatement pStat = dConnect.prepareStatement(SQL);
pStat.setString(1, fName);
pStat.setString(2, lName);
pStat.setInt(3, age);
pStat.setInt(4, xp);
pStat.setString(5, mStatus);
pStat.setString(6, dAdd);
pStat.setString(7, pNum);
pStat.setString(8, email);
pStat.setString(9, crime);
pStat.setString(10, type);
}catch(Exception sx){
System.out.println("Error is found :"+sx);
}
}
You need to execute the statement and commit these database changes by adding lines in try-catch block:
pStat.executeUpdate();
dConnect.commit();
You just need to execute the statement by adding one additional call:
pStat.executeUpdate();

JDBC ON DUPLICATE KEY UPDATE doesn't return 0

I have a little java code that uses a SQL query to INSERT, or UPDATE if it already exists.
SQL Statement:
PreparedStatement cl = c.prepareStatement("INSERT INTO client VALUES (?, ?, ?, ?, ?, ?) " +
"ON DUPLICATE KEY UPDATE sex = VALUES(sex), zip = " +
"VALUES(zip), gem = VALUES(gem), agb = VALUES(agb), dob = VALUES(dob)");
Java code:
private void clientInsert(PreparedStatement cl, String bsn, String sex, String zip, String dob, String gem, String agb) throws SQLException {
cl.setString(1, bsn);
cl.setString(2, sex);
cl.setString(3, zip);
cl.setString(4, dob);
cl.setString(5, gem);
cl.setString(6, agb);
int result = cl.executeUpdate();
System.out.println("return: " + result);
if (result == 1) System.out.println("New client inserted: " + bsn);
else if (result == 2) System.out.println("Existing client updated: " + bsn);
else if (result == 0) System.out.println("Existing client, not updated (duplicate values)");
else System.out.println("query failed");
}
It inserts fine(returning 1) and when running it again with the same "bsn"(id) but a different zip for example, it updates fine(returning 2). But when I run it again using exact same data, without changes, it returns 1 again, so I can't tell in my console wether the client already exists without changes or not.
How do I check that?

How to escape apostrophes from user input

So I'm importing information from a .csv file into a database. However I'm having trouble with the user inputted description in the csv file as they contain apostrophes which is breaking the SQL import.
My Import statement is String sqlJob =
"INSERT INTO job (ID, Job_Contact, Internal_Comment, Customer_Name,"
+ " Duration, Job_Location, Job_Completion_Date, Job_Technician,"
+ " Job_Asset, Job_Type, Job_Description) VALUES ('"
+csvRecord.get(i)+"', '"+csvRecord.get(26)+"', '"+csvRecord.get(16)
+"', '"+csvRecord.get(2)+"', '"+csvRecord.get(31)+"', '"+csvRecord.get(27)
+"', '"+csvRecord.get(28)+"', '"+csvRecord.get(29)+"', '"+csvRecord.get(30)
+"', '"+csvRecord.get(33)+"', '"+csvRecord.get(34)+"');";
A simplified form would be
"INSERT INTO job (ID, Description) VALUES ('"
+ csvRecord.get(i) + "', '" + csvRecord.get(34) + "');";
The problem is csvRecord.get(34) will sometimes contain apostrophes. For example "My name's Bob" and that apostrophe in Bob is breaking the surrounding apostrophes that are needed to declare that the value is a string for the SQL.
Is there an easy way to parse the string and add escape characters in front of apostrophes or should I format my original SQL command a different way.
Thanks!
The problem is you are assembling the SQL statement as a String, concatenating the parameter values. This is highly not advisable.
Use PreparedStatements instead that are easier to use. You can pass parameters without any modification and they won't interfere with the correct execution of the SQL statement.
Also as a valuable bonus, your code will be free of SQL Injection problems.
Example from the JDBC Tutorial:
String updateString = "update COFFEES set SALES = ? where COF_NAME = ?";
PreparedStatement updateSales = con.prepareStatement(updateString);
updateSales.setInt(1, numSales);
updateSales.setString(2, coffeeName);
updateSales.executeUpdate();
As you see, the parameters are NOT concatenated into the String, but they will take the place of the ? symbols.
Even if coffeeName has the value "Africa's Best" (apostrophe included) the query will work well.
Use PreparedStatement so you can be in save.
String name = request.getParameter( "ID" );
String message = request.getParameter( "Job_Contact" );
Connection c = null;
try
{
String url = "jdbc:mysql://localhost/**"databasename"**;
String username = "**<Database Login>**";
String password = "**<Database password>**";
**// at the ? section you can add any quantity you need to**
String sql = "insert into **<databasename>**(name, message) values (?, ?)";
c = DriverManager.getConnection( url, username, password );
PreparedStatement pstmt = c.prepareStatement( sql );
pstmt.setString( 1, name );
pstmt.setString( 2, message );
pstmt.executeUpdate();
}
catch( SQLException e )
{
throw new ServletException( e );
}
finally
{
try
{
if( c != null ) c.close();
}
catch( SQLException e )
{
throw new ServletException( e );
}
}

Categories

Resources