how to update mysql with textfield and jcombobox in java - java

private void UpdateActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
//Update
try{
if(!(jTextField1.getText().isEmpty())){
Connection myConn= null;
Statement myStmt= null;
ResultSet myRs= null;
String user= "root";
String pass= "passwd14";
//Get Connection to database
myConn = DriverManager.getConnection("jdbc:mysql://localhost:3306/company",user, pass);
//Create a Statement
myStmt = myConn.createStatement();
//Prepared Statement
PreparedStatement pst=null;
try{
String on= jTextField1.getText();
//Prepare statement Execution
String sql2 = "UPDATE amazon SET name =?, mob =?, oddt =? FROM amazon WHERE odn ='"+on+"'";
pst=myConn.prepareStatement(sql2);
//pst.setString(4,jTextField1.getText());
pst.setString(1,jTextField2.getText());
pst.setString(2,jTextField6.getText());
pst.setString(3,jTextField5.getText());
pst.executeUpdate();
//Update ComboBox
String s= (String)jComboBox1.getSelectedItem();
jComboBox1.setSelectedItem(s);
String s2= (String)jComboBox2.getSelectedItem();
jComboBox1.setSelectedItem(s2);
JOptionPane.showMessageDialog(this,"Record Saved..");
}catch (Exception e){
JOptionPane.showMessageDialog(this,"Error");
}
}
}catch (Exception ex){
JOptionPane.showMessageDialog(this," This Error.. Keeps Showing up");
}
}
This is the database I want to update :
amazon(name, mob, iss, stat, oddt, odn)
that is (name, mobile, issue, status, order_details, orderno)

Update Query
It will work
String sql2 = "UPDATE amazon SET name =?, mob =?, oddt =? WHERE odn ='"+on+"'";

Related

why doesn't it show in Jtable? i am trying to connect my database to my jtable

I can't see why this is broken I checked the url and user and password
here is my database properties
enter image description here
nothing wrong with the sql
enter image description here
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
try{
Class.forName("oracle.jdbc.OracleDriver");
//conneting my database
Connection con = DriverManager.getConnection("jdbc:oracle:thin:#localhost:1521:XE","system","sisidodo30");
Statement st = con.createStatement();
//the sql code
String sql = "SELECT * FROM \"SYSTEM\".STOCKSTABLEPROJECT";
ResultSet rs = st.executeQuery(sql);
while(rs.next()){
//for some reason it doesn't get in here
System.out.println("i am in the loop");
String Name = rs.getString("NAME");
String Price = String.valueOf(rs.getInt("PRICETODAY"));
String tbdata[] ={Name,Price};
DefaultTableModel tblModel =(DefaultTableModel)jTable1.getModel();
tblModel.addRow(tbdata);
}
con.close();
}
catch(Exception e) {
System.out.println(e.getMessage());
}
}

JavaFX - Insert form textfield to SQLite Database

I made a Form scene in my Application and wanted to insert the entered data to my SQLite Database when I hit the Save button. Here is the short code:
#FXML
private void handleSaveNewShop(ActionEvent event) {
String name = shopname.getText();
String adress = streetadress.getText();
String city = cityname.getText();
String state = statename.getText();
String country = countryname.getText();
String zip = zipcode.getText();
String phonept1 = phonecountryid.getText();
String phonept2 = phoneareaid.getText();
String phonept3 = phoneothernumber.getText().toString();
Connection conn = null;
Statement stmt = null;
try{
Class.forName("org.sqlite.JDBC");
System.out.print("\nConnecting to database...");
conn = DriverManager.getConnection("jdbc:sqlite:FranchiseManagement.sqlite");
System.out.println(" SUCCESS!\n");
/*Tried this
String insertToshopList = "INSERT INTO shopList (name, adress, city, state, country, zipcode, phonect, phonearea, phonemain)" + "values(name,adress,city,state,country,zip,phonept1,phonept2,phonept3)";
stmt.executeUpdate(insertToshopList);
*/
//And This
//stmt.executeUpdate( "INSERT INTO shopList ('name','adress','city', 'state', 'country', 'zipcode', 'phonect', 'phonearea', 'phonemain') VALUES('"+name+"','"+adress+"','"+city+"'),'"+state+"','"+country+"','"+zip+"','"+phonept1+"','"+phonept2+"','"+phonept3+"'");
conn.commit();
System.out.println(" SUCCESS!\n");
conn.close();
} catch(SQLException se) {
se.printStackTrace();
}
catch(Exception e) {
e.printStackTrace();
}
But I got NullPointException on my commited parts. The database connection seems okay and Connected.
Here is how my Database Looks:
Fixed it by removing the commit and added the INSERT into method well-formatted:
#FXML
private void handleSaveNewShop(ActionEvent event) {
String name = shopname.getText();
String adress = streetadress.getText();
String city = cityname.getText();
String state = statename.getText();
String country = countryname.getText();
String zip = zipcode.getText();
String phonept1 = phonecountryid.getText();
String phonept2 = phoneareaid.getText();
String phonept3 = phoneothernumber.getText();
Connection conn;
Statement stmt = null;
try{
Class.forName("org.sqlite.JDBC");
System.out.print("\nConnecting to database...");
conn = DriverManager.getConnection("jdbc:sqlite:FranchiseManagement.sqlite");
System.out.println(" SUCCESS!\n");
stmt = conn.createStatement();
stmt.executeUpdate( "INSERT INTO shopList ('name','adress','city', 'state', 'country', 'zipcode', 'phonect', 'phonearea', 'phonemain') VALUES('"+name+"','"+adress+"','"+city+"','"+state+"','"+country+"','"+zip+"','"+phonept1+"','"+phonept2+"','"+phonept3+"')");
//conn.commit();
System.out.println(" SUCCESS!\n");
conn.close();
} catch (ClassNotFoundException | SQLException e){
Logger.getLogger(DBConnect.class.getName()).log(Level.SEVERE, null, e);
}

Insert data to MS Access DB through JDBC-ODBC

I tried to insert some data from java to my database (ms.access) but when I click button nothing add to database. here is the code:
private void EmpButtonMouseClicked(java.awt.event.MouseEvent evt) {
String name,sex,email,username,password;
name = tfName.getText();
sex=(String) cbSex.getSelectedItem();
email=tfEmail.getText();
username=tfUser.getText();
try{
String url;
url = "jdbc:odbc:mydata";
Connection conn = DriverManager.getConnection(url,"","");
Statement stm = conn.createStatement();
stm.executeUpdate("INSERT INTO EmployeeLogin " + "VALUES (name, email, sex, username)");
conn.close();
}catch (SQLException sqlException){}
}
what wrong with that code?
I think I found the way to do it...
String sex=(String) cbSex.getSelectedItem();
try{
String url = "jdbc:odbc:mydata";
Connection conn = DriverManager.getConnection(url,"","");
String sql = "INSERT INTO CustomerLogin(Name, Email, Sex, Username, Password) VALUES(?,?,?,?,?)";
pst=conn.prepareStatement(sql);
pst.setString(1, tfName.getText());
pst.setString(2, tfEmail.getText());
pst.setString(3, sex);
pst.setString(4, tfUser.getText());
pst.setString(5, pfPassword.getText());
pst.execute();
tfName.setText("");
tfEmail.setText("");
tfUser.setText("");
pfPassword.setText("");
JOptionPane.showMessageDialog(null,"Succed Create Account! You can now return to Login Page");
}catch (Exception e){
JOptionPane.showMessageDialog(null,e); }
The Problem is :
stm.executeUpdate("INSERT INTO EmployeeLogin " + "VALUES (name, email, sex, username)");
write like :
stm.executeUpdate("INSERT INTO EmployeeLogin VALUES ("+name+", "+email+", "+sex+", "+username+")");

Deleteing data from database based on a jcomboBox throws an error

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt)
{
Connection conn=DbCon.conDB();
//String Mname =jComboBox1.getSelectedItem().toString();
String sql="delete Name from nowshowingmovie where Name = '"+jComboBox1.getSelectedItem().toString()+"'";
try{
pst=conn.prepareStatement(sql);
// pst.executeQuery();
pst.executeUpdate(sql);
JOptionPane.showMessageDialog(null,"Movie Deleted Sucessfully");
}
catch(SQLException e)
{
JOptionPane.showMessageDialog(null, e);
}
}
2 issues:
In general the syntax for DELETE is
String sql = "delete from nowshowingmovie where Name = '"+jComboBox1.getSelectedItem().toString()+"'";
PreparedStatement doesn't use the SQL String, i.e. just use pst.executeUpdate()
Side note: Since you're already using a PreparedStatement you can use a placeholder to avoid SQL injection attacks rather than using String concatenation.
String sql = "delete from nowshowingmovie where Name = ?";
pst.setString(1, jComboBox1.getSelectedItem().toString());
pst.executeUpdate();

Display rows in database using java

I was trying to display the rows in the database using Java. My idea is to sort the rows in the database and display them in 3 columns and infinite rows. This is what I have. When I run it, I couldn't see any output. Where did I go wrong?
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
import java.sql.SQLException;
public class Rows {
public static void main(String[] args) throws SQLException,ClassNotFoundException
{
Connection connection = null;
try {
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/testapp";
String user = "root";
String password = "root";
connection = DriverManager.getConnection(url, user, password);
Statement stmt = connection.createStatement();
String sql = "select * from site order by fname;";
stmt.execute(sql);
} catch (ClassNotFoundException e) {
System.err.println("Could not load database driver!");
} catch (SQLException e) {
e.printStackTrace();
}
finally
{
if (connection != null)
{
connection.close();
}
}
}
}
The database table I have is
datas(id int, fname varchar(20)
Statement stmt = connection.createStatement();
String sql = "select id, fname from site order by fname;";
ResultSet rs=stmt.executeQuery(sql);
while(rs.next()){
int id=rs.getInt("id");
.............
}
Reference: Retrieving and Modifying Values from Result Sets
The code should obtain a ResultsSet and iterate through it.
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/testapp";
String user = "root";
String password = "root";
connection = DriverManager.getConnection(url, user, password);
Statement stmt = connection.createStatement();
//You shouldn't need the semi-colon at the end
String sql = "select * from site order by fname;";
//missing piece
ResultSet rs = stmt.executeQuery(sql);
while (rs.next()) {
int id = rs.getInt("id");
String name = rs.getString("name");
System.out.println(id + "\t" + name);
}

Categories