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
Related
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 + "')";
int rs2 = s
.executeUpdate("INSERT INTO hiscores (userid, playerRights, LVL, XP, 0, 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20) VALUES ('"
+ player.getUniqueId()
+ "', '"
+ player.getStaffRights()
+ "', '"
+ player.getSkill().getTotalLevel()
+ "','"
+ player.getSkill().getTotalXp()
+ "','"
+ player.getSkill().getExp()[0]
+ "','"
+ player.getSkill().getExp()[1]
+ "','"
+ player.getSkill().getExp()[2]
+ "','"
+ player.getSkill().getExp()[3]
+ "','"
+ player.getSkill().getExp()[4]
+ "','"
+ player.getSkill().getExp()[5]
+ "','"
+ player.getSkill().getExp()[6]
+ "','"
+ player.getSkill().getExp()[7]
+ "','"
+ player.getSkill().getExp()[8]
+ "','"
+ player.getSkill().getExp()[9]
+ "','"
+ player.getSkill().getExp()[10]
+ "','"
+ player.getSkill().getExp()[11]
+ "','"
+ player.getSkill().getExp()[12]
+ "','"
+ player.getSkill().getExp()[13]
+ "','"
+ player.getSkill().getExp()[14]
+ "','"
+ player.getSkill().getExp()[15]
+ "','"
+ player.getSkill().getExp()[16]
+ "','"
+ player.getSkill().getExp()[17]
+ "','"
+ player.getSkill().getExp()[18]
+ "','"
+ player.getSkill().getExp()[19]
+ "','"
+ player.getSkill().getExp()[20] + "')");
I am not sure why my code isn't working. I'm so close! Why am I getting an error with my syntax? It looks correct to me? Could anybody please help me with this? Any help is much appreciated!
fillerfillerfillerfillerfillerfillerfillerfillerfillerfillerfiller
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '0, 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20) VALUES ('0', '0', '42','3' at line 1
I would use a PreparedStatement in this case to simplify this code:
PreparedStatement st;
st = connection.prepareStatement(""
+"INSERT INTO hiscores (userid, playerRights, LVL, XP, "
+"`0`,`1`,`2`,`3`,`4`,`5`,`6`,`7`,`8`,`9`,`10`,`11`,`12`,`13`,`14`,`15`,"
+"`16`,`17`,`18`,`19`,`20`) "
+"VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
st.setInt( 1, player.getUniqueId());
st.setString( 2, player.getStaffRights());
st.setInt( 3, player.getSkill().getTotalLevel());
st.setString( 4, player.getSkill().getTotalXp());
for(int i=0; i<=20; i++){
st.setInt( i+5, player.getSkill().getExp()[i]);
}
st.executeUpdate();
i added sqlite-jdbc-3.7.2.jar to build path. I used insert query. when i opened the wellec.db with notepad, i can see records. But my select is not working.
HERE WellInfo class properties
public Integer wellID;
public Integer measurement;
public String wellname;
public Integer wellstatus;
public String licenseno;
public String gl;
public String kb;
public String spuddate;
public String drillingenddate;
public String totaldepth;
public String notes;
public String easting;
public String northing;
public String coordinatesystem;
public Integer islogadd;
here is my createtable sql
Class.forName("org.sqlite.JDBC");
c = DriverManager.getConnection("jdbc:sqlite:wellec.db");
c.setAutoCommit(false);
System.out.println("Opened database successfully");
stmt = c.createStatement();
String sql = "CREATE TABLE IF NOT EXISTS WELLINFO " +
"(ID INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL ," +
" WELLNAME CHAR(90) NOT NULL, " +
" WELLSTATUS INT NOT NULL," +
" MEASUREMENT INT NOT NULL," +
" ISLOGADD INT NOT NULL," +
" GL CHAR(50) NOT NULL, " +
" KB CHAR(50) NOT NULL, " +
" SPUDDATE CHAR(50) NOT NULL, " +
" TOTALDEPTH CHAR(50) NOT NULL, " +
" LICENSENO CHAR(50) NOT NULL, " +
" DRILLINGENDDATE CHAR(50) NOT NULL, " +
" NOTES CHAR(150) NOT NULL, " +
" EASTING CHAR(50) NOT NULL, " +
" NORTHING CHAR(50) NOT NULL, " +
" COORDINATESYSTEM CHAR(50) NOT NULL)";
stmt.executeUpdate(sql);
...//other tables sql and stmt.executeUpdate(sql)
stmt.close();
c.commit();
here is my insert query which is working. WellInfo wi as parameter
Connection c = null;
Statement stmt = null;
try {
Class.forName("org.sqlite.JDBC");
c = DriverManager.getConnection("jdbc:sqlite:wellec.db");
c.setAutoCommit(false);
System.out.println("Opened database successfully");
stmt = c.createStatement();
String sql = "INSERT INTO WELLINFO " +
"(ID, WELLNAME, WELLSTATUS , MEASUREMENT, ISLOGADD , GL, KB, SPUDDATE, TOTALDEPTH, " +
"LICENSENO , DRILLINGENDDATE, NOTES, EASTING, NORTHING, COORDINATESYSTEM) " +
"VALUES (NULL,'" + wi.wellname + "'," + wi.wellstatus + "," + wi.measurement + "," +
"" + wi.islogadd +",'" + wi.gl + "','" + wi.kb + "','" + wi.spuddate + "'," +
"'" + wi.totaldepth + "','" + wi.licenseno + "','" + wi.drillingenddate + "', " +
"'" + wi.notes + "','" + wi.easting + "','" + wi.northing + "','" + wi.coordinatesystem + "');";
stmt.executeUpdate(sql);
stmt.close();
c.commit();
} catch ( Exception e ) {
System.err.println( e.getClass().getName() + ": " + e.getMessage() );
System.exit(0);
}
System.out.println("Records created successfully");
return 0;
here is my select
Connection c = null;
Statement stmt = null;
WellInfo[] wi = new WellInfo[60000];
WellInfo[] wi2 = new WellInfo[0];
int i = 0;
try {
Class.forName("org.sqlite.JDBC");
c = DriverManager.getConnection("jdbc:sqlite:wellec.db");
//c.setAutoCommit(false);
System.out.println("Opened database successfully");
stmt = c.createStatement();
ResultSet rs = stmt.executeQuery("select * from WELLINFO");
//c.commit();
//if(rs.getRow() > 0)
while ( rs.next() ) { //HERE IS THE PROBLEM
wi[i].wellID = rs.getInt("ID");
i++;
}
wi2 = new WellInfo[i];
for(int j = 0; j < i - 1; j++){
wi2[j] = wi[j];
}
rs.close();
stmt.close();
return wi2;
} catch ( Exception e ) {
System.err.println( e.getClass().getName() + ": " + e.getMessage() );
System.exit(0);
}
System.out.println("Operation done successfully");
return wi2;
Sorry not specify the problem. Here it is:
SELECT QUERY problem when i call rs.next(), i got the error java.lang.NullPointerException.
wi[i] is null => you can't call wi[i].wellID before you instantiate wi[i], you should do something like
wi[i] = new WellInfo() then call wi[i].wellID
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;
I am trying to insert records into SQL Server using jdbc conn (in java).
I am able to insert into SQL, if I manually copy the query statement in the java file. But its not inserting from the code?
Please help, where am I committing mistake?
PreparedStatement preparedStatement = null;
if (conn != null) {
System.out.println("Connection Successful!");
}
//Create a Statement object
Statement sql_stmt = conn.createStatement();
//Create a Statement object
Statement sql_stmt_1 = conn.createStatement();
//Result Set for Prouduct Table
ResultSet rs = sql_stmt.executeQuery("SELECT MAX(ID), MAX(RG_ID), MAX(WG_ID) FROM " + strDBName + ".[dbo].Product");
if ( rs.next() ) {
// Retrieve the auto generated key(s).
intID = rs.getInt(1);
intRG_ID = rs.getInt(2);
intWG_ID = rs.getInt(3);
}
for (int iCount = 0 ;iCount < arrListLevel_1_Unique.size(); iCount++)
{
//Result Set for Prouduct Table
sql_stmt_1.executeUpdate("\n IF NOT EXISTS(SELECT 1 FROM " + strDBName + ".[dbo].Product WHERE [Name] NOT LIKE '" + arrListLevel_1_Unique.get(iCount) + "') "
+ "\nINSERT INTO " + strDBName + ".[dbo].Product ([Name] ,"
+ "[RG_ID],[WG_ID],[Parent_Product]) "
+ "VALUES ( '" + arrListLevel_1_Unique.get(iCount) + "',"
+ + (intWG_ID + intRowIncrement) + ", " + (intWG_ID + intRowIncrement + 1) + ", 5828)");
intRowIncrement++ ;
}
rs.close();
sql_stmt.close();
sql_stmt_1.close();
//Close the database connection
conn.close();
You have two plus signs + in the fifth row:
+ + (intWG_ID + intRowIncrement) + ...
Otherwise, the problem may lie in the IF ... statement. You can try this instead:
sql_stmt_1.executeUpdate(
" INSERT INTO " + strDBName + ".[dbo].Product ([Name] ,"
+ "[RG_ID],[WG_ID],[Parent_Product]) "
+ " SELECT '" + arrListLevel_1_Unique.get(iCount) + "',"
+ (intWG_ID + intRowIncrement) + ", "
+ (intWG_ID + intRowIncrement + 1) + ", 5828 "
+ " WHERE NOT EXISTS( SELECT 1 FROM " + strDBName
+ ".[dbo].Product WHERE [Name] LIKE '"
+ arrListLevel_1_Unique.get(iCount) + "') "
) ;
I think the problem lies on the "\n", have you tried eliminating those 2 of "\n" and see if it's working?
Actually this kind of implementation (building SQL string with string concatenation) is really bad. At first is prone to SQL injection, and then secondly you will have problem if the value to be inserted contains character single quote or ampersand.
Instead, you should use "prepare statement".
And it's tidier to store the SQL string into a variable before executing it. So that you can log it (for debug purpose), roughly something like this:
String sqlCommand = "select * from " + tableName;
System.out.println(sqlCommand);
sqlStatement.executeUpdate(sqlCommand);
P.S. it is not advised to use system.out.println for debug, you should implement a proper logging system.