Why SAVE button is not saving to MySQL database in Java code - java

What's wrong with the code, no errors but still it's not saving to database, where did it go wrong?
Even if the database is created, the code won't store the values
JButton btnSave = new JButton("SAVE");
btnSave.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// Get Breed and age entered by user
String breed = textBreed.getText();
String breed_age = textAge.getText();
// Convert age into integer
int age = Integer.parseInt(breed_age);
// Connection
try {
//open connection
Class.forName("com.mysql.cj.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost/animal_db", "root", "root");
// Insert data into table
Statement stm = con.createStatement();
String dog_table = "CREATE TABLE IF NOT EXISTS breedtest" +
"(id INT NOT NULL AUTO_INCREMENT," +
"breed VARCHAR(30)," +
"age INT," +
"PRIMARY KEY (id))";
stm.executeUpdate(dog_table);
String sql = "INSERT INTO breedtest VALUES ('"+textBreed.getText()+"', "+textAge.getText()+")";
// Execute Statement
stm.executeUpdate(sql);
// display message of record inserted
JOptionPane.showMessageDialog(btnSave, "Record added");
textBreed.setText("");
textAge.setText("");
//Close connection
con.close();
}catch(Exception E) {
}
}
});
textBreed & textAge are text field from the GUI
here is a creen shot of the GUI.
enter image description here

I have amended the following lines, and it works fine
// Insert data into table
Statement stm = con.createStatement();
String dog_table = "CREATE TABLE IF NOT EXISTS breedtest" +
"(id INT NOT NULL AUTO_INCREMENT," +
"breed VARCHAR(30)," +
"age INT," +
"PRIMARY KEY (id))";
stm.executeUpdate(dog_table);
String sql = "INSERT INTO breedtest" + "(breed, age)" + "VALUES(?, ?)";
PreparedStatement brd = con.prepareStatement(sql);
brd.setString(1, textBreed.getText());
brd.setString(2, textAge.getText());
brd.execute();
data got captured in database with the confirmation message.
Displayed message
Database table
This line of code is not executing
String sql = "INSERT INTO breedtest" + "(breed, age)" + "VALUES ("+textBreed.getText()+", "+textAge.getText()+")";
but this one is.
String sql = "INSERT INTO breedtest" + "(breed, age)" + "VALUES(?, ?)";
I understand that in my first code I omitted to name the columns, thanks for flagging this.
Could someone explain me which line of code is associating the "VALUES(?, ?)" to the textfield.

You need to modify your Insert query with the following
String sql = "INSERT INTO breedtest(breed, age) VALUES ('"+textBreed.getText()+"', "+textAge.getText()+")";

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

SQL in Prepared Statement throwing SQL exception

I'm trying to figure out why this code is throwing an SQL exception. When I run this code it prints "Bad SQL in customer insert ps", which is the message in that inner catch block. I've got multiple prepared statements with SQL inserts like this both in this class and also elsewhere in my application. They're all working fine. I've looked through this one over and over again, and I can't figure out why this one is throwing an exception.
try {
Connection conn = DBconnection.getConnection();
PreparedStatement ps = conn.prepareStatement("SELECT customerId FROM customer WHERE customerName=\"" + name + "\";");
System.out.println(ps.toString());
ResultSet rs = ps.executeQuery();
if (rs.next()) {
customerId = rs.getString("customerId");
}
try {
PreparedStatement customerInsert = DBconnection.getConnection().prepareStatement("INSERT "
+ "INTO customer (customerName, addressId, active, createDate, createdBy, lastUpdate, lastUpdateBy)"
+ "VALUES(\"" + name + "\", " + addressId + ", " + active + ", UTC_TIMESTAMP(), \"" + LogInController.getUserName() + "\", UTC_TIMESTAMP(), \"" + LogInController.getUserName() + "\");");
customerInsert.executeUpdate();
System.out.println(customerInsert.toString());
System.out.println(rs.toString());
} catch (SQLException sq) {
System.out.println("Bad SQL in customer insert ps");
}
} catch (SQLException customerIdException) {
System.out.println("Bad SQL in customer ps");
}
You're using PreparedStatement as though you were using Statement. Don't put the parameters in the SQL, put in placeholder ? marks. Then use the various setXyz methods (setString, setInt, etc.) to fill in the parameters:
PreparedStatement customerInsert = DBconnection.getConnection().prepareStatement(
"INSERT INTO customer (customerName, addressId, active, createDate, createdBy, lastUpdate, lastUpdateBy)" +
"VALUES(?, ?, ?, ?, ?, ?, ?);"
);
customerInsert.setString(1, name);
customerInsert.setInt(2, addressId);
// ...etc. Notice that the parameter indexes start with 1 rather than 0 as you might expect

How do I CREATE a table and INSERT records into table using JDBC?

I am attempting to execute multiple SQL statements at once using JDBC. I am aware that the addBatch() and executeBatch() functions can be used to accomplish this. I have incorporated them into my code and even "SET NOCOUNT OFF" but my CREATE and INSERT statements were not reflected in my SQL Server database. Here is what I have attempted below:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import com.microsoft.sqlserver.jdbc.SQLServerException;
public class Excel_Java_POI_Exp_V2
{
#BeforeClass
public void setUp() throws Exception
{
//Do Nothing
}
#Test
public void testUsingExcel() throws Exception, SQLException
{
String url = "jdbc:sqlserver://localhost:1433;" + "databaseName=AdventureWorks2012;" + "integratedSecurity=true;";
try
{
//Loading the required JDBC Driver class
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
//Creating a connection to the database
Connection conn = DriverManager.getConnection(url);
//Print Connection Verification
System.out.println("Connection Established ln");
Statement query = conn.createStatement();
//Executing SQL query and fetching the result
String SQL = "SET NOCOUNT OFF;";
//CREATE A NEW SQL TABLE AFTER ESTABLISHING CONNECTION
String SQL_Create = "CREATE TABLE SELCREATEDB"
+ "(PersonID int, LastName varchar(255), FirstName varchar(255), Address varchar(255), City varchar(255));";
//INSERT 10 RECORDS WITHIN DATABASE TABLE
String SQL1 = "INSERT INTO dbo.SELCREATEDB VALUES "
+ "(\"1000\", \"Davis\", \"John\", \"3444 Mulberry Lane\", \"Oakland CA\")";
String SQL2 = "INSERT INTO dbo.SELCREATEDB VALUES "
+ "(\"1001\", \"Robinson\", \"Larry\", \"5633 Skyline Drive\", \"Annandale VA\")";
String SQL3 = "INSERT INTO dbo.SELCREATEDB VALUES "
+ "(\"1002\", \"Arafat\", \"Yasser\", \"5633 Quidbury Lane\", \"Hezburg Israel\")";
String SQL4 = "INSERT INTO dbo.SELCREATEDB VALUES "
+ "(\"1003\", \"Castro\", \"Fidel\", \"5234 Honey Tree Avenue\", \"Port Lunciana Cuba\")";
String SQL5 = "INSERT INTO dbo.SELCREATEDB VALUES "
+ "(\"1004\", \"Carter\", \"Jimmy\", \"9234 Mackel Court\", \"Lynchburg VA\")";
String SQL6 = "INSERT INTO dbo.SELCREATEDB VALUES "
+ "(\"1005\", \"Boro\", \"Kerebede\", \"2342 Memory Lane\", \"Jamestowne VA\")";
String SQL7 = "INSERT INTO dbo.SELCREATEDB VALUES "
+ "(\"1006\", \"Attenborough\", \"David\", \"3330 Peach Lane\", \"Atlanta GA\")";
String SQL8 = "INSERT INTO dbo.SELCREATEDB VALUES "
+ "(\"1007\", \"Ahmed\", \"David\", \"30499 Tressleburry Lane\", \"Tampa FL\")";
String SQL9 = "INSERT INTO dbo.SELCREATEDB VALUES "
+ "(\"1008\", \"Tramper\", \"Jamie\", \"30499 Dickens Avenue\", \"Dallas TX\")";
String SQL10 = "INSERT INTO dbo.SELCREATEDB VALUES "
+ "(\"1009\", \"Valentine\", \"Rudy\", \"8900 Spicetree Lane\", \"San Diego CA\")";
//SET PROPERTIES
query.addBatch(SQL);
//CREATE TABLE
query.addBatch(SQL_Create);
//INSERT RECORDS
query.addBatch(SQL1);
query.addBatch(SQL2);
query.addBatch(SQL3);
query.addBatch(SQL4);
query.addBatch(SQL5);
query.addBatch(SQL6);
query.addBatch(SQL7);
query.addBatch(SQL8);
query.addBatch(SQL9);
query.addBatch(SQL10);
//EXECUTE ALL COMMANDS
query.executeBatch();
//CLOSE CONNECTION
conn.close();
}
catch (SQLServerException sqe)
{
System.out.println("A result set was generated for update.");
}
catch (java.sql.BatchUpdateException bae)
{
System.out.println("Executed Queries! Terminating Connection...");
}
}
#AfterClass
public void tearDown() throws Exception
{
//Do Nothing
}
}
I am using SQL Server 2012 Standard Edition with an Established JDBC Connection to the AdventureWorks2012 database. Any help would be much appreciated. Thank You!
The code that you have is absolutely fine but the SQL statements that you've written for your INSERT's are not one of the finest. The issue was the INSERT queries in itself!
I've corrected the INSERT queries and executed the program with one change, of SQL AUTHENTICATION and the program worked with no issues.
Updated code:
public class DDLDMLStatementsinJDBC
{
public static final String URL = "jdbc:sqlserver://localhost:1433;" + "databaseName=Dummy;sendStringParametersAsUnicode=false";
public static final String DBUSER = "sa";
public static final String DBPASS = "Welcome12!";
public static void main(String[] args) throws Exception, SQLException
{
try
{
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Connection conn = DriverManager.getConnection(URL, DBUSER, DBPASS);
System.out.println("Connection Established ln");
Statement query = conn.createStatement();
String SQL = "SET NOCOUNT OFF;";
String SQL_Create = "CREATE TABLE SELCREATEDB" + "(PersonID int, LastName varchar(255), FirstName varchar(255), Address varchar(255), City varchar(255));";
String SQL1 = "INSERT INTO dbo.SELCREATEDB VALUES " + "(1000, 'Davis', 'John', '3444 Mulberry Lane', 'Oakland CA')";
String SQL2 = "INSERT INTO dbo.SELCREATEDB VALUES " + "(1001, 'Robinson', 'Larry', '5633 Skyline Drive', 'Annandale VA')";
String SQL3 = "INSERT INTO dbo.SELCREATEDB VALUES " + "(1002, 'Arafat', 'Yasser', '5633 Quidbury Lane', 'Hezburg Israel')";
String SQL4 = "INSERT INTO dbo.SELCREATEDB VALUES " + "(1003, 'Castro', 'Fidel', '5234 Honey Tree Avenue', 'Port Lunciana Cuba')";
String SQL5 = "INSERT INTO dbo.SELCREATEDB VALUES " + "(1004, 'Carter', 'Jimmy', '9234 Mackel Court', 'Lynchburg VA')";
query.addBatch(SQL);
query.addBatch(SQL_Create);
query.addBatch(SQL1);
query.addBatch(SQL2);
query.addBatch(SQL3);
query.addBatch(SQL4);
query.addBatch(SQL5);
query.executeBatch();
conn.close();
}
catch (SQLServerException sqe)
{
System.out.println("A result set was generated for update.");
sqe.printStackTrace();
}
catch (java.sql.BatchUpdateException bae)
{
System.out.println("Executed Queries! Terminating Connection...");
bae.printStackTrace();
}
}
}
Hope you are able to get the change!

How to find what id to use next in SQLite3 and Java?

I'm currently using Java and JDBC to work with SQLite. When inserting a new object into a database, how am I supposed to know which id to use or how to generate it?
Here's my code I'm using:
private void insertIntoTable() {
Connection c = null;
Statement stmt = null;
try {
Class.forName("org.sqlite.JDBC");
c = DriverManager.getConnection("jdbc:sqlite:src/test.db");
c.setAutoCommit(false);
System.out.println("Opened database successfully");
stmt = c.createStatement();
String sql = "INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY)" +
"VALUES (2 , 'Brian Brianson', 32, 'California', 60000.00);";
stmt.executeUpdate(sql);
stmt.close();
c.commit();
c.close();
} catch (Exception e) {
System.err.println(e.getClass().getName() + ": " + e.getMessage());
System.exit(0);
}
}
When I'm inserting new items, how should I find out which id I should be using to insert into the database?
INTEGER PRIMARY KEY columns automatically behave as auto increment columns, q.v. the documentation. You need only insert NULL values for the ID column and SQLite will populate the value for you. That is, use this code:
String sql = "INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY)" +
"VALUES (null, 'Brian Brianson', 32, 'California', 60000.00);";
stmt.executeUpdate(sql);

JavaFX update a Sqlite table

I am currently working on a program the function of which is to store my passwords, and this is why I am using an SQL database called Users. This database contains tables for all the users which will be using the program. Those tables have four columns:
SiteName, Username, Password, AdditionalInfo
I am having a problem updating a specific row. This is my the code I get an error with:
public static void editPassword(String user, String siteEdited, String site, String usernamej, String password, String info){
try{
System.out.println(usernamej);
Class.forName("org.sqlite.JDBC");
c = DriverManager.getConnection("jdbc:sqlite:res/Users");
c.setAutoCommit(false);
stmt = c.createStatement();
String update = "UPDATE " + user + " set Username = " + usernamej + " where SiteName = " + siteEdited;
stmt.executeUpdate(update);
stmt.close();
c.close();
}catch(Exception e){
System.err.print( e.getClass().getName() + ": " + e.getMessage());
}
}
It is in a class made specifically for dealing with the sql database and it gets the following error when I try to change the username to 'test':
java.sql.SQLException: [SQLITE_ERROR] SQL error or missing database (no such column: test)
Assuming the value you pass in for user is the name of the table, your update string is going to look like
UPDATE usertable SET Username = test where SiteName = siteEditedValue
You need to quote the string values:
UPDATE usertable SET Username = 'test' where SiteName = 'siteEditedValue'
The quick and dirty way is:
String update = "UPDATE " + user + " set Username = '" + usernamej + "' where SiteName = '" + siteEdited + "'";
However, it's much (much, much) better to use a PreparedStatement in this case:
public static void editPassword(String user, String siteEdited, String site, String usernamej, String password, String info){
try{
System.out.println(usernamej);
Class.forName("org.sqlite.JDBC");
c = DriverManager.getConnection("jdbc:sqlite:res/Users");
stmt = c.prepareStatement("UPDATE " + user + " SET Username = ? Where SiteName = ?");
stmt.setString(1, usernamej);
stmt.setString(2, siteEdited);
stmt.executeUpdate();
stmt.close();
c.close();
}catch(Exception e){
System.err.print( e.getClass().getName() + ": " + e.getMessage());
}
}
This code assumes the type of stmt is PreparedStatement, not just Statement.
As well as taking care of quoting the values for you, this will escape any sql for you, preventing the possibility of SQL-injection attacks (while these are far less of an issue in a desktop application that a web application, it's still a good habit to get into).
#griFlo I got it running with this code:
public static void editPassword(String user, String siteEdited, String site, String usernamej, String password, String info){
try{
System.out.println(usernamej);
Class.forName("org.sqlite.JDBC");
c = DriverManager.getConnection("jdbc:sqlite:res/Users");
c.setAutoCommit(false);
PreparedStatement stmt = c.prepareStatement("UPDATE " + user + " SET Username = ? Where SiteName = ?");
stmt.setString(1, usernamej);
stmt.setString(2, siteEdited);
stmt.executeUpdate(update);
c.commit();
stmt.close();
c.close();
}catch(Exception e){
System.err.print( e.getClass().getName() + ": " + e.getMessage());
}
}
I had forgotten to put c.commit();

Categories

Resources