Insert data to MS Access DB through JDBC-ODBC - java

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+")");

Related

Connection reset when unable to write into MySQL

I have this method here - whenever I comment out the MySQL section, from String query to pst.close() - the code works fine. However, if I don't, then it gives me the error of Connection Reset. I am using a socket between a client and a server for your information. How would I fix this? Or it it a problem that does not deal with MySQL?
public static String doAddUser(String username, String password, String email, String fullname) throws SQLException {
String returnStatement = "";
Connection connection = establishConnection();
if(email.isEmpty() || password.isEmpty()) {
returnStatement = "CreateFailure: Some fields are left blank. Please note that all fields are required. Please try again";
}
else {
String query = "insert into test(`username`, `password`, `email`, `fullname`) values (?,?,?,?)";
PreparedStatement pst = connection.prepareStatement(query);
pst.setString(1, username);
pst.setString(2, password);
pst.setString(3, email);
pst.setString(4, fullname);
pst.executeUpdate();
pst.close();
returnStatement = "CreateSuccess: You are now registered!";
}
return returnStatement;
}
You should probably have a connection.close() before the return.
Or, if you are in a relatively new version of JRE, you could possibly achieve the same with try-with-resource.
public static String doAddUser(String username, String password, String email, String fullname) throws SQLException {
String returnStatement = "";
try (Connection connection = establishConnection()) {
if(email.isEmpty() || password.isEmpty()) {
returnStatement = "CreateFailure: Some fields are left blank. Please note that all fields are required. Please try again";
}
else {
String query = "insert into test(`username`, `password`, `email`, `fullname`) values (?,?,?,?)";
PreparedStatement pst = connection.prepareStatement(query);
pst.setString(1, username);
pst.setString(2, password);
pst.setString(3, email);
pst.setString(4, fullname);
pst.executeUpdate();
pst.close();
returnStatement = "CreateSuccess: You are now registered!";
}
}
return returnStatement;
}
This will ensure that your connection closes when the try block finishes. However, that would require that the Connection class implements the AutoCloseable interface.
I think the connection is getting established and not getting closed, might be the issue.
Here is what works for me, as suggested by #Binaek Sarkar (I modified it a little bit):
public static String doAddUser(String username, String password, String email, String fullname) throws SQLException {
String returnStatement = "";
try {
if(email.isEmpty() || password.isEmpty()) {
returnStatement = "CreateFailure: Some fields are left blank. Please note that all fields are required. Please try again";
}
else {
Connection connection = null;
connection = MySQLConnection.dbConnector();
String query = "INSERT INTO `test`(`username`, `password`, `email`, `fullname`) VALUES (?,?,?,?)";
PreparedStatement pst = connection.prepareStatement(query);
pst.setString(1, username);
pst.setString(2, password);
pst.setString(3, email);
pst.setString(4, fullname);
pst.executeUpdate();
pst.close();
returnStatement = "CreateSuccess: You are now registered! You will redirected to the login page now. ";
}
}catch(Exception e) {returnStatement = "Invalid. Please try again!";}
return returnStatement;
}

If I execute my query through phpMyAdmin it works while it doesn't in my java program

I'm new to java and for an exam, I have to make an app that's a store for a book shop but I'm having problems with the database part of the app: my prepared statement isn't working while if I copy the query generated from it and paste it into phpMyAdmin it works perfectly.
The error the app is giving me is:
java.sql.SQLSyntaxErrorException: You have an error in your SQL
syntax; check the manual that corresponds to your MariaDB server
version for the right syntax to use near 'SET #address =
LAST_INSERT_ID(); INSERT INTO utenti (email, password, nome, cogn' at
line 1
The method that generates the error
public static void createUser(String email, String password, String nome, String cognome, long telefono, String indirizzo, int cap, String città) throws Exception{
Connection conn = MysqlConnection.getConnection();
try{
st = conn.prepareStatement("INSERT INTO indirizzi (indirizzo, cap, città) "
+ "VALUES (?,?,?); "
+ "SET #address = LAST_INSERT_ID(); "
+ "INSERT INTO utenti (email, password, nome, cognome, telefono, idindirizzo) "
+ "VALUES (?, ?, ?, ?, ?, #address);");
st.setString(1, indirizzo);
st.setInt(2, cap);
st.setString(3, città);
st.setString(4, email);
st.setString(5, password);
st.setString(6, nome);
st.setString(7, cognome);
st.setLong(8, telefono);
System.out.println(st);
st.executeUpdate();
}
catch(Exception e){
throw e;
}
finally{
try{
conn.close();
}
catch(SQLException e){
throw e;
}
}
}
The method where it's used (just a test method to see if the other one works)
private static void createUser()
{
try {
ModelUser.createUser("a#a.com", "qwertyasdfg", "Aldo", "Simone", 391234567890l, "via dietro 1/g", 37051, "Sì");
} catch (Exception e) {
e.printStackTrace();
}
}
The generated sql
INSERT INTO indirizzi (indirizzo, cap, città) VALUES ('via dietro 1/g',37051,'Sì'); SET #address = LAST_INSERT_ID(); INSERT INTO utenti (email, password, nome, cognome, telefono, idindirizzo) VALUES ('a#a.com', 'qwertyasdfg', 'Aldo', 'Simone', 391234567890, #address);
A little edited for readability
INSERT INTO indirizzi (indirizzo, cap, città)
VALUES ('via dietro 1/g',37051,'Sì');
SET #address = LAST_INSERT_ID();
INSERT INTO utenti (email, password, nome, cognome, telefono, idindirizzo)
VALUES ('a#a.com', 'qwertyasdfg', 'Aldo', 'Simone', 391234567890, #address);
I think that this should be working since the query itself is working when it's put into phpMyAdmin
You are actually trying to execute two queries with one prepared statement. change your method like following
public static void createUser(String email, String password,
String nome, String cognome, long telefono, String indirizzo,
int cap, String città) throws Exception{
Connection conn = MysqlConnection.getConnection();
try{
PreparedStatement st = conn.prepareStatement("INSERT INTO indirizzi
(indirizzo, cap, città) VALUES (?,?,?)");
st.setString(1, indirizzo);
st.setInt(2, cap);
st.setString(3, città);
st.executeUpdate();
/* You may want to close PreparedStatement here */
st = conn.prepareStatement("INSERT INTO utenti
(email, password, nome, cognome, telefono, idindirizzo)
VALUES (?, ?, ?, ?, ?, LAST_INSERT_ID())");
st.setString(1, email);
st.setString(2, password);
st.setString(3, nome);
st.setString(4, cognome);
st.setLong(5, telefono);
st.executeUpdate();
/* You may want to close PreparedStatement here */
}catch(Exception e){
throw e;
}finally{
try{
conn.close();
}
catch(SQLException e){
throw e;
}
}
}

Getting Java mysql SQL Syntax error but my query seems normal

I am developing a simple java mysql based application and during data insertion into the database I'm getting an SQL error mentioned below.
Here is my code:
public DBConnection() {
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/myDatabase?useUnicode=true&useLegacyDatetimeCode=false&serverTimezone=Turkey", "root", "");
st = con.createStatement();
System.out.println("CONNECTED!");
} catch (Exception e) {
System.out.println("Error : " + e);
}
}
public void addCustomer(String name, String surname, String company, String adress, String adressTwo){
String addQuery = "insert into musteri (name,surname,company,adress,adressTwo) values (?,?,?,?,?)" ;
try {
st.executeUpdate(addQuery);
System.out.println("Data Added");
} catch (Exception e) {
System.out.println("Error occured when adding value to database : " + e );
}
}
Here is my java main method that add's the data:
public static void main(String[] args) {
// TODO code application logic here
Customers c1 = new Customers();
c1.setIsim("test");
c1.setSoyisim("test");
c1.setSirket("test");
c1.setAdres("test");
c1.setIletisim("test");
DBConnection db = new DBConnection();
db.addCustomer(c1.isim, c1.soyisim, c1.sirket, c1.adres, c1.iletisim);
}
The error I'm getting is:
Error occured when adding value to database : java.sql.SQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ''insert into musteri (ad,soyad,sirket,adres,iletisim) values (?,?,?,?,?)'' at line 1
You are mixing statements with prepared statements. You should use a prepared statement and set the values to it:
public void addCustomer(String name, String surname, String company, String address, String adressTwo) {
String addQuery = "insert into musteri (name, surname, company, adress, adressTwo) values (?,?,?,?,?)" ;
// Shown here for simplicitly.
// The query could be prepared once and stored in a data member
try (PreparedStatement ps = con.prepareStatement(addQuery)) {
ps.setString(1, name);
ps.setString(2, surname);
ps.setString(3, company);
ps.setString(4, address);
ps.setString(5, addressTwo);
ps.executeUpdate();
System.out.println("Data Added");
} catch (Exception e) {
System.out.println("Error occured when adding value to database : " + e );
}
}
May I suggest you implement addCustomer like this. Use a local Statement and create it by using try-with-resource style and then set your parameters for the query
public void addCustomer(String name, String surname, String company, String adress, String adressTwo){
String addQuery = "insert into musteri (name,surname,company,adress,adressTwo) values (?,?,?,?,?)" ;
try (PreparedStatement stmt = con.prepareStatement(addQuery)) {
stmt.setString(1, name);
stmt.setString(2, surname);
stmt.setString(3, company);
stmt.setString(4, adress);
stmt.setString(5, adressTwo);
stmt.executeUpdate();
System.out.println("Data Added");
} catch (Exception e) {
System.out.println("Error occured when adding value to database : " + e );
}
}

connecting javaprogram to mysql database

String dburl = "jdbc:mysql://localhost:3306/librarymanagementsystem";
String user = "nandika";
String password = "nandika";
public void createConnection(int id, String name, String author, String
publisher) {
try {
Connection mycon = DriverManager.getConnection(dburl);
Statement mystmt = mycon.createStatement();
String sql = "insert into addbook" + "(Book ID,Book
Name,Author,Publisher)" + "values" + "(" + id + "," + name + "," +
author + "," + publisher + ")";
mystmt.executeUpdate(sql);
System.out.println("updated");
} catch (Exception ex) {
}
execute update is a method in another class.there seem to be
whats the wrong with this code segment? database is not updating!!
You have not loaded the database drivers, to do that include this code:
Class.forName("com.mysql.jdbc.Driver");
If you haven't drivers download and put in project library.
Their are some problems with this code snippet. One is you didn't load the database. Also you didn't use the username and password.
I recommend you to create the database connection separately. Maybe in a separate Java file. As below,
public class DatabaseConnection {
public static Statement getConnection() throws Exception{
Class.forName("com.mysql.jdbc.Driver"); //Loading the database
Connection c = DriverManager.getConnection("jdbc:mysql://localhost:3307/restaurentsystem","nandika","nandika"); //username and password can save as variables and pass here
Statement statement = c.createStatement();
return statement;
}
}
Then you can use it whenever you want. In this situation,
try {
Statement s = DatabaseConnection.getConnection();
s.executeUpdate("INSERT INTO addbook (Book ID, Book Name, Author, Publisher) VALUES (?, ?, ?, ?);"); //Values should assign here.
System.out.println("updated");
} catch (Exception e) {
System.out.println(e);
}
This is what I do if I do this. I recommend you to try this method.
This is the way you should be doing it, with preparedStatement to prevent injections
String dburl = "jdbc:mysql://localhost:3306/librarymanagementsystem";
String user = "nandika";
String password = "nandika";
private PreparedStatement preparedStatement;
private Connection con = null;
public static void main(String[] args) {
}
public void createConnection(int id, String name, String author, String publisher) {
try {
con = DriverManager.getConnection(dburl, user, password);
String stmt = "INSERT INTO addbook (Book ID,Book Name,Author,Publisher) VALUES (?, ?, ?, ?)";
preparedStatement = con.prepareStatement(stmt);
preparedStatement.setInt(1, id);
preparedStatement.setString(2, name);
preparedStatement.setString(3, author);
preparedStatement.setString(4, publisher);
preparedStatement.executeUpdate();
con.close();
System.out.println("updated");
} catch (Exception ex) {
}

how to update mysql with textfield and jcombobox in 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+"'";

Categories