how to insert value from jtable to mysql? - java

Im trying to insert data from jtable to database!! the first three columns(stafftimetableid,staffname,staffid) are inserted from the jtexfield(no errors found,successfully added) but when im trying to insert from jtable it promts a java.null pointerExcetion error !!
I have no errors in database connection !!
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
if (jComboBox1.getSelectedItem().equals("Staff Time Table"))
{
try
{
PreparedStatement pst =null;
Connection con = clerkpanell.DBConnection.connectDB();
String data=jTable2.getValueAt(0,1).toString();
String sql = "insert into stafftimetable (StaffTimeTableID,StaffName,StaffID,7.50-8.30) values ('"+ttid.getText()+"','"+staffname.getText()+"','"+staffid.getText()+"','"+data+"');";
pst=con.prepareStatement(sql);
pst.executeUpdate();
// JOptionPane.showMessageDialog(null,"Added");
}
catch (Exception e)
{
JOptionPane.showMessageDialog(null,e);
}
}

In this statement String sql = "insert into stafftimetable (StaffTimeTableID,StaffName,StaffID,7.50-8.30) values ('"+ttid.getText()+"','"+staffname.getText()+"','"+staffid.getText()+"','"+data+"');";
Please store the ttid.getText(), staffname.getText(),staffid.getText()into separate variables. Something like this,
String ttid=ttid.getText();
String staffname = staffname.getText();
String staffid = staffid.getText();
and then the insert statement should be something like this
String sql = "insert into stafftimetable (StaffTimeTableID,StaffName,StaffID,7.50-8.30) values ('"+ttid.+"','"+staffname+"','"+staffid+"','"+data+"');";

Related

How to search in a string saved in MySQL database

I have created a JList by taking inputs from user in jtextField. Then I have saved the jList to Mysql database by converting the JList to String as I want to save the JList item in a single row as single entry.
code for adding user input to jList:
DefaultListModel dlm= new DefaultListModel();
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
String userInput= jTextField2.getText();
dlm.addElement(userInput);
jList1.setModel(dlm);
jTextField2.setText(null);
}
Code Used for saving the JList into MySQL database as String:
String allitem=null;
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
for(int i = 0;i<jList1.getModel().getSize();i++)
{
allitem = (String)jList1.getModel().getElementAt(i)+"::"+allitem;
}
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/ft", "root", "");
PreparedStatement stmt = conn.prepareStatement("insert into ftt (listname,listitem) values (?,?)");
stmt.setString(1, jTextField1.getText());
stmt.setString(2, allitem);
stmt.execute();
conn.close();
}catch(
Exception e)
{
JOptionPane.showMessageDialog(null, e);
e.printStackTrace();
}
JOptionPane.showMessageDialog(null, "done");
}
Now in the next page user can view all the Strings (Jlist is saved as String) item in the JList. I wan to disaplay user the details of the JList item selected. I have created a Jtable and want to display the other details of the JList item selected.
Code I have Tried:
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {
Update_table1();
}
private void Update_table1(){
try{
Class.forName("com.mysql.jdbc.Driver");
Connection conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/ft","root","");
String query="SELECT listname FROM ftt WHERE listitem=?;";
PreparedStatement prepstmt=conn.prepareStatement(query);
String s = (String) jList1.getSelectedValue();
prepstmt.setString(1,s);
ResultSet rs=prepstmt.executeQuery();
jTable3.setModel(DbUtils.resultSetToTableModel(rs));
}catch(Exception e){
JOptionPane.showMessageDialog(null, e);
}
}
But when using this code the Jtable is not showing any value although it is taking the table header name. Please can anyone check I correct in how to search in the String saved in MySQL database. I think the problem is there as other things are working fine.
note: Its not showing any error or exception.
It is not the best way to keep record as the way you are doing as concatenated string. You better use a normalized table and keep all list elements as a record. For your code you are trying to query on a field which contain concatenated information. So you may use "like" keyword instead of "=".
"SELECT listname FROM ftt WHERE listitem like %?%;"

SQL Error or missing database syntax error

I get an sql error when trying to insert something into my DB.
I give a bunch of input to my method, convert that input into strings or sql time and want to store it.
public static void setCourseList(String courseDescription, String courseName, LocalTime courseStart, LocalTime courseEnd, LocalDate courseDate, DayOfWeek courseDay) {
Connection conn = null;
try {
// db parameters
// path to db relative to run time directory
String url = "jdbc:sqlite:Holiday.db";
String sqlInsertCourse = "INSERT INTO COURSE (Name,Start,End,Date,Day,Description) VALUES (?, ?,?, ?,?, ?,);";
conn = DriverManager.getConnection(url);
System.out.println("Connected");
Statement stmt = conn.createStatement();
PreparedStatement pstmt = conn.prepareStatement(sqlInsertCourse);
pstmt.setString(1, courseName);
String courseStartString = courseStart.toString();
pstmt.setString(2, courseStartString);
java.sql.Time courseEndTime = Time.valueOf(courseEnd);
pstmt.setTime(3, courseEndTime);
java.sql.Date courseDateDate = java.sql.Date.valueOf(courseDate);
pstmt.setDate(4, courseDateDate);
String courseDayString = courseDay.toString();
pstmt.setString(5, courseDayString);
pstmt.executeUpdate();
pstmt.close();
System.out.println("Connection to SQLite has been established.");
// create tables if they do not exists
stmt.execute(sqlInsertCourse);
} catch (SQLException e) {
System.out.println(e.getMessage());
} finally {
try {
if (conn != null) {
conn.close();
}
} catch (SQLException ex) {
System.out.println(ex.getMessage());
}
}
}
I would expect it to store the input in my db.
I do get an [SQLITE_ERROR] SQL error or missing database (near ")": syntax error) error instead.
Any help is appreciated.
I am new to sql.
Change
String sqlInsertCourse = "INSERT INTO COURSE (Name,Start,End,Date,Day,Description) VALUES (?, ?,?, ?,?, ?,);";
To
String sqlInsertCourse = "INSERT INTO COURSE (Name,Start,End,Date,Day,Description) VALUES (?, ?,?, ?,?, ?);"; //<<<<<<<<<< extra comma removed
As per the comment on the line the final comma after the last ? has been removed.
Same as what Mike has answered, you can change it to
String sqlInsertCourse = "INSERT INTO COURSE (Name,Start,End,Date,Day,Description) VALUES (""put values here"");";
If you are wondering why it doesn't throw you an error, it's because there is no syntax error in the java, there's an error in the SQL which only the database can throw, but you're computer can't recognize. Hope this answers your question.

java - cant insert multiple data to database

i have some code that will save into two database but the other one can't saving into database. the one that can't to save is inserting multiple row data from jtable with 3 values but i have 5 columns in database because i need to fill it temporary with the other values are null. this is the code :
private void btnSimpanActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
try{
String sql="INSERT INTO pinjam VALUES('"+noPeminjaman.getText()+
"','"+noMember.getText()+"','"+tglPinjam.getText()+"',1)";
java.sql.Connection conn = (Connection)Config.configDB();
java.sql.PreparedStatement pst = conn.prepareStatement(sql);
pst.execute();
//Simpan ke pinjam_detil
int rows = tabelPinjam.getRowCount();
for(int row = 0; row<rows; row++){
String idBuku = (String)tabelPinjam.getValueAt(row, 0);
String tglTempo = (String)tabelPinjam.getValueAt(row, 2);
try{
String query = "INSERT INTO pinjam_detil (idpinjam,idbuku,tgl_tempo) "
+ "VALUES(?,?,?)";
java.sql.PreparedStatement stmt = conn.prepareStatement(query);
stmt.setString(1, noPeminjaman.getText());
stmt.setString(2, idBuku);
stmt.setString(3, tglTempo);
stmt.addBatch();
stmt.executeBatch();
}catch(Exception ex){}
}
JOptionPane.showMessageDialog(null, "Successfully Save");
}catch(Exception e){}
resetForm();
}
Don't catch an exception and do nothing. Preferably, add a throws clause to the method, like so:
private void doThingie() throws SQLException {}
and if that's not an option, this should be in your catch block:
new RuntimeException(e);
because right now some error is happening and you can't tell because you're silently ignoring it.
Also, it's just stmt.execute();, not addBatch+executeBatch

How to delete a record (string) JAVA and MYSQL

I successfully can delete an integer but when I tried to make it a STRING it says
"unknown column itemtodelete in where clause but my ITEMTODELETE is a STRING declared in the database not an integer how much It doesn't delete a STRING?
below is my code:
private void DeleteButtonActionPerformed(java.awt.event.ActionEvent evt) {
int del = (prompt):
if (del == JOptionPane.YES_OPTION){
DelCurRec();
}
}
public void DelCurRec() {
String id = field.getText();
String SQL = "DELETE FROM inventory WHERE ItemCode = "+id+" ";
try {
Class.forName(connectio);
} catch (Exception e) {
JOptionPane.showMessageDialog(null,""+e.getMessage(),"JDBC Driver Error",JOptionPane.WARNING_MESSAGE);
}
Statement stmt = null;
Connection con = null;
//Creates connection to database
try {
con = DriverManager.getConnection("Connection");
stmt = con.createStatement();
} catch (Exception e) {
JOptionPane.showMessageDialog(null,""+e.getMessage(),"Connection Error",JOptionPane.WARNING_MESSAGE);
}
//Execute the SQL statment for deleting records
try {
stmt.executeUpdate(SQL);
//This closes the connection to the database
con.close();
//This closes the dialog
JOptionPane.showMessageDialog(null,"Deleted Succesfully","Delete Successful",JOptionPane.WARNING_MESSAGE);
} catch (Exception e) {
JOptionPane.showMessageDialog(null,""+e.getMessage(),"Communication Error",JOptionPane.WARNING_MESSAGE);
}
}
Do NOT use a Statement use a PreparedStatement instead, otherwise your application will be vulnerable to SQL injections. E.g. someone enters a string like: "'; drop table inventory; --"
The corresponding prepared statment would look something like:
String SQL = "DELETE FROM inventory WHERE ItemCode = ? ";
PreparedStatement pstmt = null;
// get a connection and then in your try catch for executing your delete...
pstmt = con.prepareStatement(SQL);
pstmt.setString(1, id);
pstmt.executeUpdate();
try changing the line:
String SQL = "DELETE FROM inventory WHERE ItemCode = "+id+" ";
to
String SQL = "DELETE FROM inventory WHERE ItemCode = '"+id+"' ";
I think you need to pass Integer.parseInt(id) and not id...assuming your id is int
This worked for me:
Statement stmt=con.createStatement();
stmt.executeUpdate("DELETE FROM student WHERE reg_number='R18854';");

How to change the database name and table using java?

i try to understand this part of code:
Properties details= new Properties();
details.load(new FileInputStream("details.properties"));
String userName = details.getProperty("root");
String password = details.getProperty("mysqlpassword");
String url = "jdbc:mysql://localhost/test";
Class.forName ("com.mysql.jdbc.Driver").newInstance();
conn = DriverManager.getConnection (url, userName, password);
System.out.println ("Database connection established");
PreparedStatement st = conn.prepareStatement("insert into 'Email_list' values(?)");
for(String mail:mails)
i understand that test database is a default database. but if i want to use an existing database, i will just modify test to another database name isn't it?
If yes how do i modify my code if my new database is Test2 with table name Email which contains mail column with varchar(100)
i try to replace test by Test2 Email_list by Email but i don't know where to put the column name mail.
Thank you for help
The INSERT statement you use omits the columns.
INSERT INTO tablename VALUES (1, 2, 3)
can be written if the table has three columns and for all three columns values are provided.
If some columns can be left empty or have default values, you can write
INSERT INTO tablename (column1, column2) VALUES (1, 2)
In this cas the value for column3 is null or the default value.
So in your case the column name is put nowhere.
You are missing PORT number in your connection string...
String url = "jdbc:mysql://localhost/test"; should be String url = "jdbc:mysql://localhost:PORT_NUMBER/test"; like String url = "jdbc:mysql://localhost:3306/test";
Let me know if you have any queries...
Also, Check below how Prepared Statement works
import java.sql.*;
public class TwicePreparedStatement{
public static void main(String[] args) {
System.out.println("Twice use prepared statement example!\n");
Connection con = null;
PreparedStatement prest;
try{
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql:
//localhost:3306/jdbctutorial","root","root");
try{
String sql = "SELECT * FROM movies WHERE year_made = ?";
prest = con.prepareStatement(sql);
prest.setInt(1,2002);
ResultSet rs1 = prest.executeQuery();
System.out.println("List of movies that made in year 2002");
while (rs1.next()){
String mov_name = rs1.getString(1);
int mad_year = rs1.getInt(2);
System.out.println(mov_name + "\t- " + mad_year);
}
prest.setInt(1,2003);
ResultSet rs2 = prest.executeQuery();
System.out.println("List of movies that made in year 2003");
while (rs2.next()){
String mov_name = rs2.getString(1);
int mad_year = rs2.getInt(2);
System.out.println(mov_name + "\t- " + mad_year);
}
}
catch (SQLException s){
System.out.println("SQL statement is not executed!");
}
}
catch (Exception e){
e.printStackTrace();
}
}
}
Good Luck!!!

Categories

Resources