inserting to database using java gui - java

I am trying to insert data from my netbeans to mysql workbench. there is no problem with the query but when I run the program a message box appear "Unknown column 'empJob' in 'field list '" . What seems to be the problem?
and just to Know i tried this on another table and it works just fine! but in this one it doesn't work!
int id, Salary;
String name, Address, Jop;
id = Integer.parseInt(tNo.getText());
name = tName.getText();
Address = tAddress.getText();
Jop = tJop.getText();
Salary = Integer.parseInt(tNo.getText());
String sql = "insert into employee(empid,empName, empAddress,empJob,empSalary) values('" + id + "','" + name + "' , '" + Address + "','" + Jop + "','" + Salary + "')";
Statement st = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
int x = st.executeUpdate(sql);
if (x > 0) {
JOptionPane.showMessageDialog(prev, x + "rows effected");
} else {
JOptionPane.showMessageDialog(prev, "insert failed");
}

Do you have a typo? You write empJob -> but your variable is called Jop. So maybe it should be empJop.
String sql = "insert into employee(empid,empName, empAddress,empJop,empSalary) values('" + id + "','" + name + "' , '" + Address + "','" + Jop + "','" + Salary + "')";

Related

MySQL deleting code data in Eclipse

I have tables in MySQL and did make connection with this database from Eclipse. I can insert my information into my tables in my MySQL database, but I want the code that can help me for I delete some information from there.
I have this code for inserting but I need the code for deleting:
try {
DriverManager.registerDriver(new com.mysql.jdbc.Driver());
Connection connection = (Connection) DriverManager.
getConnection("jdbc:mysql://localhost/fish", "root", "test");
Statement s = (Statement) connection.createStatement();
s.executeUpdate("insert into fish.store(tr_no,tr_day,tr_month,tr_year,age_type," +
"class,pa_no,first_name,second_name,last_name,age,birth_place," +
" tele_no,address,gender,booking_status) values" +
"('" + fl_no + "','" + day + "','" + month + "','" +
year + "','" + age_type + "','" + fcl + "','" + spa + "'," +
"'" + sfirst + "','" + ssecond + "','" + slast + "','" + sage +
"','" + sP_O_B + "','" + sphone + "'," +
"'" + saddress + "','" + sgender + "','" + status + "')");
Ticket t = new Ticket(sfirst, slast, ssecond, ifl, fcl, day2, month2, year2);
t.setSize(830, 380);
t.setVisible(true);
t.setLocationRelativeTo(null);
t.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
ImagePanel panel = new ImagePanel(new ImageIcon("2.jpg").getImage());
t.getContentPane().add(panel);
} catch(SQLException ex) {
Logger.getLogger(fish.class.getName()).log(Level.SEVERE, null, ex);
}
You can use something like this:
//initialize connection...
String deleteString = "DELETE FROM fish.store WHERE first_name = ? AND last_name = ?";
PreparedStatement deleteStmt = null;
try {
//...
deleteStmt = connection.prepareStatement(deleteString);
deleteStmt.setString(1, "Clint");
deleteStmt.setString(2, "Eastwood");
deleteStmt.executeUpdate();
connection.commit();
} catch...
//close connection
Of course you have to replace the replacement of the statement with your own conditions (deleteStmt.set... (http://docs.oracle.com/javase/7/docs/api/java/sql/PreparedStatement.html)) and the WHERE clause of the SQL.
Have a look at http://dev.mysql.com/doc/refman/5.1/de/delete.html and http://docs.oracle.com/javase/tutorial/jdbc/basics/prepared.html

Get the next ID in Access database(now the ID is M15, i want get M16)

My Access Database memberID now is M15 , i want to get the next memberID M16 , how to get it and display in a text field ?
String query;
query = "INSERT INTO Membership VALUES ('" +memberID_a.getText() + "','" +memberName_a.getText() + "','" + icNo_a.getText() + "','" + gender_a.getText() +"','" + birthday_a.getText() +"','" + telephoneNo_a.getText() + "','" + mobileNo_a.getText() + "','" + email_a.getText() + "','" + address_a.getText() + "','" + postalCode_a.getText() + "','" + state_a.getText() + "','" + country_a.getText() + "','" + memberPoint_a.getText() + "');";
try{
stmtInsert = conn.createStatement();
stmtInsert.executeUpdate(query);
} catch(Exception ex){
JOptionPane.showMessageDialog(null,"ERROR"+ex.toString(),"ERROR",JOptionPane.ERROR_MESSAGE);
}
query = "INSERT INTO Membership VALUES ('" +memberID_a.getText() + "','" +memberName_a.getText() + "','" + icNo_a.getText() + "','" + gender_a.getText() +"','" + birthday_a.getText() +"','" + telephoneNo_a.getText() + "','" + mobileNo_a.getText() + "','" + email_a.getText() + "','" + address_a.getText() + "','" + postalCode_a.getText() + "','" + state_a.getText() + "','" + country_a.getText() + "','" + memberPoint_a.getText() + "');";
NEVER, EVER do that.
http://en.wikipedia.org/wiki/SQL_injection
instead use
query = "INSERT INTO Membership VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?)";
Where each ? is a placeholder.
http://docs.oracle.com/javase/tutorial/jdbc/basics/prepared.html
Anyway, the important thing to realise about database tables is that the order of the rows is meaningless unless you use an 'order by' clause in your query. So if you want to order by the id column, use
SELECT * from Membership ORDER BY id;

Java sql populating table and getting '.0' at the end

im using this code to populate my jtable with data from database:
String sql = "SELECT "
+ "a.pranesimo_pav AS 'Pavadinimas', a.sukurimo_data AS 'Sukurtas' , b.gavimo_data AS 'Gavimo data'"
+ "FROM Pranesimas a "
+ "INNER JOIN "
+ "( "
+ "SELECT pranesimo_id, gavimo_data "
+ "FROM Pranesimo_siuntimas_vienam_zmogui "
+ "WHERE vardas_pavarde = '" +vardas_pavarde+ "' "
+ "UNION ALL "
+ "SELECT pranesimo_id, gavimo_data "
+ "FROM Pranesimo_siuntimas_grupei "
+ "WHERE grupes_pav = '" +grupes_pav+ "'"
+ ")b ON a.pranesimo_id = b.pranesimo_id ";
pst = conn.prepareStatement(sql);
rs = pst.executeQuery(sql);
antraspanelesamipranesimaiTable.setModel(DbUtils.resultSetToTableModel(rs));
}
It does the job, but at the end of my 'datetime' value, it adds '.0' at the end of it, for example:
value in database - '2013-01-20 02:50:00'
value i get in my table - '2013-01-20 02:50:00.0'
how can i fix this?

Sql update query with Single quotes

I am using hibernate application in java to retrieve and update database.
During updating a table,i forming an sql query as follows,
String qry = "UPDATE " + entity + " SET " + htmlColumn + " ='"+value+"' WHERE " + id + " = " + primaryId;
where value is a html string which contains single quotes sometimes.
How to escape ignore/escape the single quotes and update the table successfully
Thanks
use PreparedStatement for this
String qry = "UPDATE " + entity +
" SET " + htmlColumn + " = ? " +
"WHERE " + id + " = ?";
PreparedStatement pstmt = con.prepareStatement(qry);
pstmt.setString(1, value);
pstmt.setInt(2, primaryId);
pstmt.executeUpdate();
PreparedStatement
Don't set values directly.
currentSession()
.createQuery("UPDATE " + entity + " SET " + htmlColumn +
" = :value WHERE " + id + " :id")
.setParameter("value", value).setParameter(":id",id).executeUpdate();
You can replace the single quote with a double single quote. value.replace("'","''"); but you will need to cater for more than just that because your value can easily allow for SQL Injection if it is not properly catered for.
You can use preparedstatement as :
String query= "UPDATE " + entity + " SET " + htmlColumn + " =? WHERE " + id + " = " + primaryId;
PreparedStatement ptmt = con.prepareStatement(query);
ptmt.setString(1, value);

General error when trying to insert data into database

I am trying to insert data into a database and once again I cant seem to get to the bottom as to why I am getting a general error.
Any advice as to how to overcome this problem.
Class.forName(driverName);
connection = DriverManager.getConnection(SourceURL, user, password);
int rowAdded;
Object typeId = comboKeys.getSelectedItem();
String typeIdString = typeId.toString();
int typeIdInt = Integer.parseInt(typeIdString);
String animalIDString = txtAnimalID.getText();
int animalID = Integer.parseInt(animalIDString);
System.out.println(animalID);
String name = txtName.getText();
Statement statement = connection.createStatement();
String queryString = "INSERT INTO Animal (animalID, name, typeIDForeign) VALUES (" + animalID + ", '" + name + "', '" + typeIdInt + "')";
rowAdded = statement.executeUpdate(queryString);
connection.close();
Kind regards
Arian
Error
You have typeIdInt as Integer, however in the sql query, you are stating it as string (because you surround it with single quotes)
Solution
String queryString = "INSERT INTO Animal (animalID, name, typeIDForeign) VALUES (" + animalID + ", '" + name + "', '" + typeIdInt + "')";
should be :
String queryString = "INSERT INTO Animal (animalID, name, typeIDForeign) VALUES (" + animalID + ", '" + name + "', " + typeIdInt + ")";
Look at " + typeIdInt + ". You have '" + typeIdInt + "'
Good Luck!!!

Categories

Resources