I want to insert a time which is taken from a textbox to the mysql database TIME column. I suppose I need to convert String to TIME like converting String to Date in mysql using "STR_TO_DATE" in the query. I looked for answers but I didn't get the answer I required.
Edit: SQL from comments:
"insert into schedules (
courseid,
batch,
subjectid,
teacherid,
stime,
etime,
date,
location,
building,
department,
hall,
status
) values ('" +
getCourse() + "','" +
getBatch() + "', '" +
getSubject() + "','" +
getTeacher() + "', '" +
getStime()+ "','" +
getEtime()+
"',STR_TO_DATE('" + getDate() + "','%d-%m-%Y'),'" +
getLocation() + "', '" +
getBuilding() + "', '" +
getDepartment()+ "', '" +
getHall() +
"','ACTIVE')"
As stated in comments Mysql accepts simple strings like '05:12:59' into TIME type columns but lets try to have another answer to it to. Check the format of date you get from textbox and edit Simple date format. You can try below.
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
Date parsedDate = dateFormat.parse(request.getParameter("textBoxName"));
Timestamp timestamp = new java.sql.Timestamp(parsedDate.getTime());//or you can assign this stuff to stime variable
I assume you are using preparedStatement as I think you will inserting many times. If so you can set the parameter like this.
preparedStatement.setTimestamp(1, timestamp);//1 is the index of parameter you can choose named parameters too
Also you can choose the to set stime and pass it in query using its relative getter.
Related
I can't find a way of putting all the selected items on 3 different combobox which I need to insert as query to Java DB(derby). Here's my code.
int response = JOptionPane.showConfirmDialog
(null, "Do you want to add the employee?","Confirm",JOptionPane.YES_NO_OPTION,JOptionPane.QUESTION_MESSAGE);
if(response == JOptionPane.YES_OPTION){
try{
String url="jdbc:derby://localhost:1527/EMPLOYEEINFO [ADMIN1 on ADMIN1]";
String username="ADMIN1";
String password="ADMIN1";
Connection con = DriverManager.getConnection(url, username, password);
Statement stat = con.createStatement();
String Query =
"INSERT INTO EMPLOYEE (EMPLOYEE_ID,EMP_LASTNAME,EMP_FIRSTNAME,EMP_MIDDLENAME,ADDRESS,POSITION ) "
+"VALUES "
+ "(' "+AddEmployee_EmployeeID_TxtField.getText()+" ',"
+ " ' "+AddEmployee_LastName_TxtField.getText()+" ',"
+ " ' "+AddEmployee_FirstName_TxtField.getText()+" ',"
+ " ' "+AddEmployee_MiddleName_TxtField.getText()+" ',"
+ " ' "+AddEmployee_Address_TxtField.getText()+" '"
+ " ' "+AddEmployee_Position_TxtField.getText()+" ',"
+ " ' "+AddEmployee_Gender_ComboBox.getSelectedItem()+"')"
;
stat.execute(Query);
JOptionPane.showMessageDialog(null,"Insert Success!");
And below is the screenshot. I'm thinking of getselectedObject but i have 3 combo boxes so I really don't know how. Please help.
I need to get the selected items of Month, Day and Year of the Birthday then insert it to my table in Derby. Thanks in advance.
You should create a separate method to get the fields and combine the values into a formatted date. Something like this:
private String getDateFromFields() {
String month = monthComboBox.getSelectedItem();
String day = dayComboBox.getSelectedItem();
String year = yearComboBox.getSelectedItem();
// Format this the way your database expects.
String formattedDate = month + "/" + day + "/" + year;
}
You just call this method and you will get back the formatted date string that you can use in your query. Change the variable names of the combo box fields to match your names and format the string into what your database expects and you should be good to go!
You can do something like this:
String bDay=dayCombo.getSelectedItem()+"-"+monthCombo.getSelectedItem()+"-"+yearCombo.getSelectedItem();
But I will recommend you to use JDatechooser in this case.
JDateChooser bDayChooser =new JDateChooser();
bDayChooser.setDateFormatString("dd-MM-yyyy");//format visible date of the date chooser as you need
String bDay=((JTextField) bDayChooser.getDateEditor().getUiComponent()).
getText();
I have a MySQL database and want to write a row into it. The problem is that MySQL do not like my query, why? This is my code:
java.sql.Timestamp date = new java.sql.Timestamp(new java.util.Date().getTime());
for (Integer articlevalue : articlesendlist) {
for (Integer suppliervalue : suppliersendlist) {
connection.executeQuery("INSERT INTO Bestellungen(Bestellung_ID, Artikel_ID, Lieferant_ID, Datum, Preis) VALUES (" + maxorder + ", " + articlevalue + ", " + suppliervalue + ", " + date + ", NULL)");
}
}
A small description for my code. The articlesendlist contains IDs from selected values from a JTabel. The same applies to the suppliersendlist. I want to write the IDs into the table "Bestellung". The variable maxorder is the current ID for the table "Bestellung".
If you need it, the exception is:
You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server version for the right syntax to use
near '12:45:06.164, NULL)' at line 1
Please do not comment/answer with other links, I already searched for the problem and read several sites. They do not help me or are not suitable for my problem.
Thank you for help
Exception is obvious isn't it.
You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server version for the right syntax to use
near '12:45:06.164, NULL)' at line 1
You are not using quotes around date field.
However you should really avoid executing your SQL queries like this and use PreparedStatemens for this purpose.
PreparedStatemens has specific methods like setDate, setTime, setLong, setString etc and you don't need to worry about putting right quotes in your code.
Try changing this line:
connection.executeQuery("INSERT INTO Bestellungen(Bestellung_ID, Artikel_ID, Lieferant_ID, Datum, Preis) VALUES (" + maxorder + ", " + articlevalue + ", " + suppliervalue + ", " + date + ", NULL)");
to this:
connection.executeQuery("INSERT INTO Bestellungen(Bestellung_ID, Artikel_ID, Lieferant_ID, Datum, Preis) VALUES ('" + maxorder + "','" + articlevalue + "','" + suppliervalue + "','" + date + "','NULL')");
public static void updateHistory(Client winner) {
try {
if (winner != null) {
getDatabase().newQuery("INSERT INTO tournaments (`players`, `winner`, `winnerKills`, `map`, `prize`) VALUES ('" + tournyPlayers.size() +"', '" + winner.playerName + "', '" + winner.killCount + "', 'Wilderness', '" + winner.gameScore + "')");
}
else {
getDatabase().newQuery("INSERT INTO tournaments (`players`, `winner`, `winnerKills`, `map`, `prize`) VALUES ('" + tournyPlayers.size() +"', 'None', 'None', 'Wilderness', 'None')");
}
ArrayList<Client> player = tournyPlayers;
for (int i = 0; i < player.size(); i++) {
if (player.get(i).killedByPlayer == "") {
getDatabase().newQuery("INSERT INTO tournament_players (`name`, `kills`, `killedBy`, `score`, `points`) VALUES ('" + player.get(i).playerName + "', '" + player.get(i).killCount + "', 'N/A', '" + player.get(i).gameScore + "', '" + player.get(i).gamePoints + "')");
}
else {
getDatabase().newQuery("INSERT INTO tournament_players (`name`, `kills`, `killedBy`, `score`, `points`) VALUES ('" + player.get(i).playerName + "', '" + player.get(i).killCount + "', '" + player.get(i).killedByPlayer + "', '" + player.get(i).gameScore + "', '" + player.get(i).gamePoints + "')");
}
}
} catch (SQLException e) {
e.printStackTrace();
}
}
Well what I am trying to do is, insert a new tournament row, which will display the information about the tournament, now I want to add the players to the tournament (Who was playing it), so I now will add each player, into a new row, with his data.
But now I want to make sure that the player matches the current tournament I inserted. I can't make a unique number of the current server, server-sided because the server may go down, and lose the count.
therefore I've thought of using the inserted tournaments table's auto_increment ID, and add it along with the inserted player, so his id will be tournament's auto increment id.
Is there a way to fetch the auto increment ID without using the exact same data I inserted into the tournaments (cause there may be 2 tournaments with the same status, who knows).
Is there a way to do so?
I was thinking of adding a MD5 hash with the date + time, to the tournaments row and then add it to the player's row, is that a good solution?
Take a look at Statement#getGeneratedKeys() which returns a ResultSet that you can use to retrieve any generated primary keys as
ResultSet rsKeys = statement.getGeneratedKeys();
if (rsKeys.next()) {
tournament.setId(rsKeys.getLong(1));
}
Please, note that you need to give a hint to the JDBC driver that you would like to retrieve the generated keys while preparing a PreparedStatement as
connection.prepareStatement(strSQL, Statement.RETURN_GENERATED_KEYS);
or, at the time of executing a Statement as
statement.executeUpdate(strSQL, Statement.RETURN_GENERATED_KEYS);
Reference:
Statement#getGeneratedKeys()
Retrieves any auto-generated keys created as a result of executing this Statement object. If this Statement object did not generate any keys, an empty ResultSet object is returned.
I have a need to use Statement.executeUpdate() to insert data into Database.
So every parameter must be embeded into a SQL string.
In Database, the type of two columns are datetime: Date1 and Date2
At client side, if I use following statement:
String SQLString = "INSERT INTO Position (" +
......
"Date1, " +
......
"Date2) " +
"VALUES(" +
......
//"2012-05-29 16:28:58.555" + ", " + // runtime error, always say error at 16
//"2012-05-29" + ", " + // no runtime error, but lost time and result date is also not correct
//"10-06-02" + ", " + // no runtime error, but it adds 2 days beginning at 1900-01-01 00:00:00.000
......
null
")";
Can anyone tell me how to correctly embedded Datetime into SQL String?
You should use a PreparedStatement and pass the date field ad Date ...
String SQLString = "INSERT INTO Position (Date1) VALUES (?)";
PreparedStatement prest = con.prepareStatement(SQLString);
prest.setDate(1,new Date());
prest.executeUpdate()
First up, you have to use PreparedStatement. Then you could do something like:
statement.setDate(2, new Date());
I am trying to insert a date object into the database but it says im trying to insert an Integer. Here is my code:
public void insertAssignment(long studentId, String newAssignment, int ptsTotal, int ptsRecieved, String category, Date dueDate, String term, int yr) {
java.sql.Date temp = new java.sql.Date(dueDate.getTime());
try{
s.execute("INSERT INTO Assignments " +
"VALUES (" + studentId + ",'" + newAssignment + "'," + ptsTotal +
"," + ptsRecieved + ",'" + category + "'," + temp
+ ",'" + term + "'," + yr + ")");
System.out.println("Assignment inserted.");
}
catch(SQLException error){
System.err.println("Unable to insertAssignment.");
error.printStackTrace(System.err);
System.exit(0);
}
}
My error:
java.sql.SQLSyntaxErrorException: Columns of type 'DATE' cannot hold values of type 'INTEGER'.
To do this, use a prepared statement instead and use a setter.
Currently you flatten your date to a string value (which needs to be in the right format for the database for this to work) and lose that it is a date so the database needs to parse it. You avoid this using the prepared statement.