How to add date to database from java - java

I am having trouble trying to add dates to my database
This is my code
public void AddStudent(String idStudent, String name, String idClass, String dateOfBirth, String sex, String address){
Connection connect = classConnection.connect;
PreparedStatement ps = null;
String query = "insert into students values(?,?,?,?,?,?)";
try {
ps = connect.prepareStatement(query);
ps.setString(1, idStudent);
ps.setString(2, name);
ps.setString(3, sex);
ps.setString(4, dateOfBirth);
ps.setString(5, address);
ps.setString(6, idClass);
ps.execute();
} catch (SQLException e) {
JOptionPane.showMessageDialog(this, "Error: " + e.toString());
}
}
This is an error
conversion failed when converting date and/or time from character string
I have to solve it like, thanks

You need to parse it fist to date, on the same format as your database format().
For shortcut, you can use setDate from PreparedStatement;
hope this helps

Related

SQL syntax error : correspond to your MariaDB server for the right syntax

When I click on the Create button to add a supplier record in to my database, I receive the above error message.
Can someone help me where did I went wrong: is there something wrong with the insert statement.
private void jbtnCreateActionPerformed(java.awt.event.ActionEvent evt) {
try {
String sql = "INSERT INTO supplier"
+"(Full Name, Address Line 1, Address Line 2, Post Code, Email Address, Phone Number)"
+"VALUES (?,?,?,?,?,?)";
connection = DriverManager.getConnection("jdbc:mysql://localhost/inventory management", "root", "");
ps = connection.prepareStatement(sql);
ps.setString(1, txtname.getText());
ps.setString(2, txtaddressline1.getText());
ps.setString(3, txtaddressline2.getText());
ps.setString(4, txtpostcode.getText());
ps.setString(5, txtemail.getText());
ps.setString(6, txtphone.getText());
ps.executeUpdate();
JOptionPane.showMessageDialog(null, "Supplier Added");
} catch(SQLException | HeadlessException ex) {
JOptionPane.showMessageDialog(null, ex);
}
}
You have whitespaces in the column names (as well as in the connection string) which is not allowed. If you really need to use column names with spaces, put them in backticks:
String sql = "INSERT INTO supplier"
+"(`Full Name`, `Address Line 1`, `Address Line 2`, `Post Code`, `Email Address`, `Phone Number`)"
+"VALUES (?,?,?,?,?,?)";
However, it would be better to use snake case for the column names: full_name, etc.

java.sql.SQLTransientConnectionException: HikariPool-1- connection is not available

I am a newbie assigned to build a hostel management application using HikariPool connection. Now, i sometimes get this error java.sql.SQLTransientConnectionException: HikariPool-1- connection is not available and once it happens, it messes up my application data. For instance, in my code below, i call the function paymentRecord() in my AssignRoom() to execute after a room is assigned.
I open and close connections in each functions(AssignRoom() and paymentRecord()) but sometimes, one of the functions fail to execute. It is either AssignRoom() executes correctly and paymentRecord() fails to execute or vice versa.
My code may be very bad but i am newbie trying to learn.
PS: Now i never had this issue when i was testing the application with good internet connection , but my Client did report this and he mostly has internet connectivity problem.
I sometimes think the internet connection might be a factor to my problem, if so why do i deal with this please?
Assigning Room
public void AssignRoom(){
try
{
java.sql.Date sqldate = new java.sql.Date(date.getDate().getTime());
conn = DBConnection.getConn();
String query = "Insert into AssignRoom(Floor,RoomNumber,Student,DateAssigned) values (?,?,?,?)";
PreparedStatement pst = conn.prepareStatement(query);
pst.setString(1, Floor.getSelectedItem().toString());
pst.setString(2, FindRoom.getSelectedItem().toString());
pst.setString(3, FindStd.getSelectedItem().toString());
pst.setDate(4, sqldate);
pst.execute();
if(seats.getText().equals("0")){
JOptionPane.showMessageDialog(null, "Room is fully occupied");
}
else
{
JOptionPane.showMessageDialog(null, "Room Successfully Assigned");
UpdateAvailableBeds();
paymentRecord();
conn.close();
JOptionPane.showMessageDialog(null, "Please wait...Processing payment");
navToPayment();
}
}
catch(Exception ex)
{
JOptionPane.showMessageDialog(null, ex);
}
}
Payment Record
public void paymentRecord()
{
try
{
java.sql.Date sqldate = new java.sql.Date(date.getDate().getTime());
System.out.println("Cheking "+sqldate);
System.out.println("Cheking "+FindRoom.getSelectedItem().toString());
System.out.println("Cheking "+FindStd.getSelectedItem().toString());
conn = DBConnection.getConn();
String query = "Insert into PaymentRecords(Student_Name,Room_Number,DateAssigned,Total_Amount,Paid,Balance) values(?,?,?,?,?,?)";
String sql = "select Price from Rooms where RoomNumber =" +FindRoom.getSelectedItem()+ " and Floor ='"+Floor.getSelectedItem().toString()+"'";
PreparedStatement pst = conn.prepareStatement(query);
PreparedStatement pst1 = conn.prepareStatement(sql);
// ResultSet rs = pst.executeUpdate(query);
ResultSet rs1 = pst1.executeQuery(sql);
while(rs1.next())
{
FullAmount = rs1.getString("Price");
Price = Float.parseFloat(FullAmount);
Rem = Float.parseFloat(AmtPaid.getText());
Balance = Price - Rem;
System.out.println("Cheking "+FullAmount);
}
pst.setString(1, FindStd.getSelectedItem().toString());
pst.setString(2, FindRoom.getSelectedItem().toString());
pst.setDate(3, sqldate);
pst.setString(4, FullAmount);
pst.setString(5, AmtPaid.getText());
pst.setFloat(6, Balance);
pst.execute();
pst1.execute();
conn.close();
}
catch(Exception ex)
{
JOptionPane.showMessageDialog(null, ex);
}
}

Java JDBC Prepared Statement not inserting single quotes (SQL Escaping)

I have the following method to a person into the database which later is used to create a person object:
public static void addPerson(String personCode, String firstName, String lastName,
String phoneNo, String street, String city, String state,
String zip, String country) {
Connection conn = database.com.airamerica.interfaces.DatabaseConnect.getConnection();
PreparedStatement ps;
ResultSet rs;
String addAddressQuery = "INSERT INTO `Addresses` (`street`,`city`,`state`,`zip`,`country`) VALUES (?,?,?,?,?)";
String checkAddress = "SELECT `address_ID` FROM `Addresses` WHERE street = ? AND city = ? AND state = ? AND zip = ? AND country = ?";
String addPersonQuery = "INSERT INTO `Persons` (`personCode`,`firstName`,`lastName`,`address_ID`,`phoneNumber`) VALUES (?,?,?,(SELECT `address_ID` FROM `Addresses` WHERE street = ? AND city = ? AND state = ? AND zip = ? AND country = ?),?)";
try
{
ps = conn.prepareStatement(checkAddress);
ps.setString(1, street);
ps.setString(2, city);
ps.setString(3, state);
ps.setString(4, zip);
ps.setString(5, country);
rs = ps.executeQuery();
if(!(rs.next())){
ps = conn.prepareStatement(addAddressQuery);
ps.setString(1, street);
ps.setString(2, city);
ps.setString(3, state);
ps.setString(4, zip);
ps.setString(5, country);
ps.executeUpdate();
ps.close();
}
ps.close();
rs.close();
ps = conn.prepareStatement(addPersonQuery);
ps.setString(1, personCode);
ps.setString(2, firstName);
ps.setString(3, lastName);
ps.setString(4, street);
ps.setString(5, city);
ps.setString(6, state);
ps.setString(7, zip);
ps.setString(8, country);
ps.setString(9, phoneNo);
ps.executeUpdate();
ps.close();
conn.close();
}
catch (SQLException e)
{
System.out.println("SQLException: ");
e.printStackTrace();
throw new RuntimeException(e);
}
}
The problem is when we insert a name like Miles O'Brien it gets inserted as Miles O'Brien I tried to escape using a method to replace the single quote (apostrophe) with two of them ('') for escaping. That method just caused data to be inserted as Miles O''Brien. How do we go about fixing this? The problem is at ps.setString(3, lastName); How do we get the last name into the database without it going in as '?
just in case you need it the engine is InnoDB and we are using default UTF8 as the collation.
As you can see the last name is passed to the method as well.
GIGO
A step debugger and a well placed break point or the following will show you that this is not related to JDBC at all.
A step debugger is the much preferred way to inspect running code!
public static void addPerson(final String personCode, final String firstName, final String lastName,
final String phoneNo, final String street, final String city, final String state,
final String zip, final String country) {
System.out.println(String.format("Last Name = %s",lastName));
// the rest of your code
}

Insert sql query not inserting row in db

I am inserting a new row in db, there is no exception in the console. But the row is not inserted into the table.
String name = request.getParameter("name");
String city = request.getParameter("city");
String country = request.getParameter("country");
String query = "INSERT INTO `test`.`student`(Name,City,Country)VALUES(?,?,?);";
PreparedStatement ps = (PreparedStatement) con.prepareStatement(query);
ps.setString(1,name);
ps.setString(2,city);
ps.setString(3,country);
ps.executeUpdate();
ps.close();
No need of casting the PreparedStatement again in connecting the query. It should be like
Connection conn = getDBConnection();
PreparedStatement ps = con.prepareStatement(query);
Remove the ; from the query inside the doublequotes
Prefer concatenation operator ( + sign) while using single quotes inside double quoted strings in the query
Here is a sample code that I have tested and working fine. Compare it with your code to know what you are doing wrong.
public void insertRowToDB(int staffID, String first_name, String last_name, int department_ID) {
Connection dbConnection = null;
try {
dbConnection = DatabaseConnection.getconnection();
if (!dbConnection.isClosed()) {
String sql = "INSERT INTO staff (staffID,first_name,last_name,department_ID) VALUES(?,?,?,?)";
PreparedStatement statement = dbConnection.prepareStatement(sql);
statement.setInt(1, staffID);
statement.setString(2, first_name);
statement.setString(3, last_name);
statement.setInt(4, department_ID);
statement.executeUpdate();
}
} catch (SQLException ex) {
Logger.getLogger(DatabaseConnection.class.getName()).log(Level.SEVERE, null, ex);
} finally {
try {
if (dbConnection!=null) {
if (!dbConnection.isClosed()) {
dbConnection.close();
}
}
} catch (SQLException ex) {
Logger.getLogger(DatabaseConnection.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
A priori view of your code, there is no the commit statement.
You need to perform this statement right before the ps.close() line.
Best regards!

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