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);
}
Related
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());
}
}
I'm trying to set up JDBC but I'm getting this error.
I tried adding the dependency in pom.xml and even jar file nothing works. I tried the methods mentioned in previous questions, nothing works.
public class FilmLength {
public static void main(String[] args) throws SQLException {
Connection dbCon = null;
PreparedStatement st = null;
ResultSet rs = null;
String url = "jdbc:mysql//localhost:3306/sakila";
String username = "devuser";
String password = "Demo#123";
String query = "select * from film ";
try {
Class.forName("com.mysql.jdbc.Driver");
dbCon = DriverManager.getConnection(url,username,password);
st = dbCon.prepareStatement(query);
rs = st.executeQuery();
while(rs.next()) {
String title = rs.getString(1);
System.out.println(title);
}
} catch (Exception e) {
e.printStackTrace();
}
finally {
dbCon.close();
st.close();
rs.close();
}
}
}
Instead of
String url = "jdbc:mysql//localhost:3306/sakila";
it should be
String url = "jdbc:mysql://localhost:3306/sakila";
updated
try
{
sqlite.setDbPath(dbPath);
con = sqlite.connect();
if(!con.isClosed())
{
String query="SELECT Username,Password FROM Apps WHERE Username ='"+username+"'"; // and Password='"+password+"'";
ResultSet rs = con.createStatement().executeQuery(query);
while(rs.next())
{
if(rs.getString("Username").equals(username))//confronto se Username รจ gia esistente
{
trovato = true;
risultato = "gia' presente";
}
}
if(trovato==false) {
createUsers(username,password,name,surname,email,appname,ip,authorized,token);
risultato="inserito";
}
if(con!=null)
{
con.close();
}
if(sqlite != null)
{
sqlite.close();
}
if(rs != null)
{
rs.close();
}
}
In try catch block I've open connection with database embedded but in first time i don't close all connection..
With if control the program close all open connection and works well
Update 2
Here is an abbreviated version using try-with-resource instead. Code is simpler and shorter
public String RegisterUser(... ) {
boolean trovato = false;
int authorized=0;
SqliteConnection sqlite = new SqliteConnection();
String dbPath="C:/Users/l.pellegrini/eclipse-workspace/ClayAPI_dbembedded/claydb.db";
String query="SELECT Username,Password FROM Apps WHERE Username ='"+username+"' and Password='"+password+"'";
try (java.sql.Connection con = sqlite.connect();
Statement statement = con.createStatement();
Statement updStatement = con.createStatement();
) {
ResultSet rsActiveServices = con.createStatement().executeQuery(query);
// handle result set as before
} catch(SQLException e) {
e.printStackTrace();
System.out.println("errore" + e);
}
if(trovato==false) {
createUser(username, password, name, surname, appname, email, ip)
}
return "username: " + username;
}
private createUser(String username, String password, String name, String surname, String appname, String email, String ip {
String query1="INSERT INTO Apps (Username,Password,Name,Surname,Email,AppName,Ip,Authorized,Token) VALUES ('" + username + "'," + "'" +password +"','" + name + "','" + surname + "','" +email + "','" + appname + "','"+ip+"','"+authorized+"','"+token+"')";
SqliteConnection sqlite = new SqliteConnection();
String dbPath="C:/Users/l.pellegrini/eclipse-workspace/ClayAPI_dbembedded/claydb.db";
try (java.sql.Connection con = sqlite.connect();
Statement statement = con.createStatement();) {
updStatement.executeUpdate(query1);
} catch(SQLException e) {
e.printStackTrace();
System.out.println("errore" + e);
}
}
It could very well be that your prepared statement isn't properly closed. Change
ResultSet rsActiveServices = con.createStatement().executeQuery(query);
to
statement = con.createStatement();
ResultSet rsActiveServices = statement.executeQuery(query);
where statement is declared before try
java.sql.Connection con = null;
Statement statement = null;
and then close it in your finally clause
finally
{
try
{
statement.close();
con.close();
sqlite.close();
}
Update 1
I just noticed that your are trying to close your objects twice which is wrong, remove the first set of close calls and only close within finally {} at the end.
Resolved
I do errors with open and close connection in Main.. With SQLite the connection you have to open and close everytime it's carried out a query of all type(Insert, Delete,Update ecc..)
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+"'";
Below shows an error message I am receiving when trying to run my code:
sun.jdbc.odbc.JdbcOdbcStatement cannot be cast to java.sql.ResultSet
I don't understand why this error is occurring so could someone give me the reason why or even better give me a fix to the problem. Below is the entire code
public void actionlogin()
{
btnLogin.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
String username = txtUserName.getText();
String password = txtPassword.getText();
String databaseUsername = "";
String databasePassword = "";
String dataSourceName = "securitySystem";
String dbUrl = "jdbc:odbc:" + dataSourceName;
try{
//Type of connection driver used
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
//Connection variable or object param: dbPath, userName, password
Connection con = DriverManager.getConnection(dbUrl, "", "");
Statement statement = con.createStatement();
statement.execute("select username, password from securitySystem.employees");
while (((ResultSet) statement).next()) {
databaseUsername = ((ResultSet) statement).getString("username"); //resultSet.getString("username");
databasePassword = ((ResultSet) statement).getString("password");
}
statement.close();
con.close();
}catch (Exception e){
System.out.print("Out!" +e);
}
You need to use statement.executeQuery and this will return the ResultSet.
So you need to write something like that:
ResultSet rs = statement.executeQuery("select....");
while (rs.next()) {
databaseUsername = rs.getString("username");
databasePassword = rs.getString("password";
}