How can I delete a record in access from java? I have tried the following but it doesn't seem to work.
public void Delete() throws SQLException {
st.executeUpdate("DELETE FROM [AssignmentDetails] WHERE ([Entry Date],[Project ID],[Employee],[Hours Worked],[Firm Deadline],[Description of Assignment],[Additional Details],[ID]) = ('" + AbstractVariables.getEntryDate() + "','" + AbstractVariables.getProjectID() + "','" + AbstractVariables.getEmployee() + "','" + AbstractVariables.getHoursWorked() + "','" + AbstractVariables.getFirmDeadline() + "','" + AbstractVariables.getDescription() + "','" + AbstractVariables.getAdditionalDetails() + "','"+AbstractVariables.getID() + "')");
}
try {
Connection con;
Statement stmt;
String url = "jdbc:odbc:GameData.mdb";
// DATABASE CONNECTION MAGIC :-)
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con = DriverManager.getConnection(url, "user", "password");
stmt = con.createStatement();
// DELETE SOME SOME STUDENT DATA (RARELY USED IN GOOD PRACTICE)
stmt.executeUpdate("delete from students where phone = '000-0000'");
// DATABASE CLOSE/CLEANUP
stmt.close();
con.close();
}
catch(Exception e) {
e.printStackTrace();
}
You should use a parameterized query using JDBC instead of making it all one big string
PreparedStatement st=connection.createStatement("DELETE FROM [AssignmentDetails] WHERE [Entry Date]=?, [Project ID]=?, etc...);
Then set the parameters on the prepared statement and then execute it
Related
public void actionPerformed(ActionEvent arg0) {
String departurecity = depcity.getText();
String depdate = dt.getText();
String arrivalcity = ac.getText();
String arrivaldate = dtar.getText();
String cabinclass = ccc.getText();
String seats = sts.getText();
String price = prc.getText();
try {
Connection connection = (Connection) DriverManager.getConnection("jdbc:mysql://localhost:8080/airblue", "root", "");
java.sql.Statement st = connection.createStatement();
String query = "INSERT INTO flight values('" + departurecity + "','" + depdate + "','" + arrivalcity + "','" +
arrivaldate + "','" +cabinclass + "','" + seats +"','"+price+ "')";
Statement sta = (Statement) ((java.sql.Connection) connection).createStatement();
int x = ((java.sql.Statement) sta).executeUpdate(query);
JOptionPane.showMessageDialog(btnNewButton,
"done");
connection.close();
} catch (Exception exception) {
exception.printStackTrace();
}
}
});
Here is a little part of my connection code ,I have tried many solutions but none of them worked for me any solution to this problem?
Check your connection string, sometimes there might be a character after the semicolon in
mysql://
Check your db url here and you will see for yourself: https://www.soscisurvey.de/tools/view-chars.php
Maybe type out that part by hand.
I'm using twitter4j's streaming API to collect tweets. I'm doing this on java platform. I'm getting a stream of tweets at console but can't store.
public void onStatus(Status status) {
try
{
String myDriver = "org.gjt.mm.mysql.Driver";
String myUrl = "jdbc:mysql://localhost/twitterapi";
Class.forName(myDriver);
Connection conn = DriverManager.getConnection(myUrl, "twitterapi", "");
String query = " insert into tweets"
+ "(tweet_id,tweet_text,screen_name)" + " values"
+ "('" + status.getId() + "','" +
status.getText() + "', '" +
status.getUser().getScreenName() +"')";
Statement statement = conn.createStatement();
statement.executeUpdate(query);
conn.close();
}
catch (Exception e)
{
System.err.println("Got an exception!");
System.err.println(e.getMessage());
}
System.out.println("onStatus #" + status.getUser().getScreenName() + " - " + status.getText());
}
Please consider every other thing to be correct since that's already working.
In your insert you have a different number of columns to values. You are not specifying the author_id.
In addition, as DaveH noticed, you're not actually running the SQL command against the server.
I am a beginner in android development. This is a part of my sign up code in my first android studio app: The code is going into catch right after the first execute query line and not executing my second query. If i check the Database a user is added but not a fan.
Any idea why? Any help is appreciated.
try {
Connection con = connectionClass.CONN();
if (con == null) {
z = "Error in connection with SQL server";
} else {
Statement stmt = con.createStatement();
String query1 = "INSERT INTO Usertb Values ('" + userid + "', '" + Password + "', '" + 1 + "')";
stmt.executeQuery(query1);
String query = "INSERT INTO Fan Values ('" + FirstName + "', '" + LastName + "','" + Age + "', '" + Email + "', '"
+ null + "', '" + i + "', '" + null + "')";
rs = stmt.executeQuery(query);
if (rs.next()) {
z = "Sign Up successfull";
isSuccess = true;
}
}
} catch (Exception ex) {
isSuccess = false;
z = "Exceptions";
}
One has to use executeUpdate (INSERT/UPDATE) instead of executeQuery.
String sql = "INSERT INTO Usertb(userid, passw, n) VALUES (?, PASSWORD(?), ?)";
try (PreparedStatement stmt = con.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS)) {
stmt.setString(1, userName);
stmt.setString(2, password);
stmt.setInt(3, 1);
int updateCount = stmt.executeUpdate(query1); // 1 when 1 record inserted
if (updateCount != 0) {
// If you want to use an autincrement primary key:
try (ResultSet rsKeys = stm.getGeneratedKeys()) {
if (rsKeys.next()) {
long id = rsKeys.getLong(1);
}
}
}
} // Closes stmt
Furthermore it is very important to use prepared statements to prevent SQL injection. It also takes care of single quotes and backslash in the strings.
Additionally there is shown how to use AUTOINCR fields, to retrieve a database generated key, for example for the second INSERT.
For the second use a new PreparedStatement.
Passwords should better be stored encrypted in the database, should someone steal the data. You might look into that subject. My solution is quite minimal, look for seeding and other encryption functions.
I am trying to read from a mysql table and I am doing the following:
protected void pushRegisteredStudentsData() {
try {
conn = (Connection) DriverManager.getConnection(DB_URL, USER, PASS);
stmt = conn.createStatement();
String userID = "SELECT * FROM STUDENT";
rs = stmt.executeQuery(userID);
while (rs.next()) {
int id = rs.getInt("ID");
this.studentID = id;
String insertSql = "INSERT INTO REGISTEREDSTUDENTS(StudentID, ModuleCode) VALUES ('" + studentID + "', + '"
+ this.moduleCode + "')";
System.out.println("Inserting into REGISTEREDSTUDENTS.. [" + id + "]" + "[" + this.moduleCode + "]");
stmt.executeUpdate(insertSql);
}
} catch (SQLException e) {
}
}
..but for some reason,
while (rs.next()) {
int id = rs.getInt("ID");
always returns the same ID, even though the table has different ID's on every line!
Does anyone have an idea why that might be?
Thank you in advance! :(
EDIT:
I was using a single statement to execute 2 updates, which was causing the problem!
It is a bit weird that it returns always the same value because it should only return the first value ONCE.
If you print the stacktrace instead of just catching the exception and doing nothing, you will see that it will print something like:
java.sql.SQLException: Operation not allowed after ResultSet closed
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1073)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:987)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:982)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:927)
at com.mysql.jdbc.ResultSetImpl.checkClosed(ResultSetImpl.java:794)
You are using THE SAME statement for a Select and then for an Insert. This causes the resultSet that is "attached" to the Statement to close because it is not supposed to be used again.
It can be easily fixed by creating another statement:
String insertSql = "INSERT INTO REGISTEREDSTUDENTS(StudentID, ModuleCode) VALUES ('" + studentID + "', + '"
+ this.moduleCode + "')";
System.out.println("Inserting into REGISTEREDSTUDENTS.. [" + id + "]" + "[" + this.moduleCode + "]");
Statement stmt2 = conn.createStatement();
stmt2.executeUpdate(insertSql);
I am trying to insert values from one server to another using java program. Here is my code:-
public static void main(String[] args) throws FileNotFoundException {
// TODO code application logic here
try {
Class.forName("oracle.jdbc.OracleDriver");
} catch (Exception exception) {
}
Connection conn = null;
Connection conn1 = null;
ResultSet rs, rs1 = null;
Statement pst = null;
try {
// dbConnect.executequery(sdate, edate);
conn = DriverManager.getConnection("jdbc:oracle:thin:#31.4.224.76:1521:RPTPSG", "pihist", "pihist");
String query = "select * from messagemasterhistory where ROWNUM<=1572660";
// String query="select * from messagemasterhistory where createdate>='28-JAN-11' and createdate<='18-FEB-2011'";
pst = conn.createStatement(java.sql.ResultSet.TYPE_FORWARD_ONLY, java.sql.ResultSet.CONCUR_READ_ONLY);
// String sql="insert into test(SRN ,UTR) values (";
// pst=conn.prepareStatement(sql);
// rs.absolute(2000);
// pst.setFetchSize(2000);
// pst.setMaxRows(1500000);
pst.setFetchDirection(ResultSet.FETCH_FORWARD);
rs = pst.executeQuery(query);
// String statment="insert into test(UTR,SRN) values('abc','1')";
// PrintWriter wt=new PrintWriter("ritima2.txt");
conn1 = DriverManager.getConnection("jdbc:oracle:thin:#31.4.224.81:1521:RPTPSG", "rptr", "rptr");
Statement stat1 = conn1.createStatement();
while (rs.next()) {
String str = rs.getString("FIELDDATA");
String str1 = rs.getString("FIELDINFO");
String statment = "insert into MESSAGEMASTERHISTORY2(UTR,CREATEDATE,SENDER,RECEIVER,SUBMESSAGETYPE,FIELDINFO,FIELDDATA,DUPLICATE) values(" + "'" + rs.getString("UTR") + "'" + "," + "TO_DATE('" + rs.getDate("CREATEDATE") + "'" + ",'YYYY-MM-DD\" \"HH24:MI:SS')" + "," + "'" + rs.getString("SENDER") + "'" + "," + "'" + rs.getString("RECEIVER") + "'" + "," + "'" + rs.getString("SUBMESSAGETYPE") + "'" + "," + "'" + str1 + "'" + "," + "'" + str + "'" + "," + rs.getInt("DUPLICATE") + ")";
// String statment="insert into test1 (fielddata,utr) values("+"'"+(rs.getString("fielddata"))+"'"+","+"'"+rs.getString("UTR")+"')";
System.out.println(count);
stat1.executeQuery(statment);
System.out.println(str);
System.out.println(str1);
// System.out.println(rs.getClob("FIELDDATA"));
System.gc();
count++;
}
conn1.commit();
conn1.close();
// wt.close();
System.out.println("Completed");
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
After inserting few rows (6274) it gives error"java.sql.SQLException: ORA-00917: missing comma
at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:113)
at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:331)
at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:288)
at oracle.jdbc.driver.T4C8Oall.receive(T4C8Oall.java:754)
at oracle.jdbc.driver.T4CStatement.doOall8(T4CStatement.java:210)
at oracle.jdbc.driver.T4CStatement.executeForRows(T4CStatement.java:963)
at oracle.jdbc.driver.OracleStatement.doExecuteWithTimeout(OracleStatement.java:1192)
at oracle.jdbc.driver.OracleStatement.executeQuery(OracleStatement.java:1315)
at javaapplication2.Main.main(Main.java:73)
One of the Strings you are copying from the source database probably has an illegal SQL code sequence in it.
You should consider using a PreparedStatement with parameters instead of constructing the SQL using String concatenation. The PreparedStatement should be pre-compiled, and you don't need to worry about escaping your Strings.
Something like:
String statment = "insert into MESSAGEMASTERHISTORY2(UTR,CREATEDATE,SENDER,RECEIVER,SUBMESSAGETYPE,FIELDINFO,FIELDDATA,DUPLICATE) values(?,?,?,?,?,?,?,?)";
PreparedStatement ps = conn1.prepareStstement(statement)
while (rs.next()) {
ps.setString(1, rs.getString("UTR"));
ps.setDate(2, rs.getDate("CREATEDATE"));
// etc etc
ps.executeUpdate();
conn1.commit(); //maybe you want this outside the loop
}
See http://docs.oracle.com/javase/tutorial/jdbc/basics/prepared.html
That's not a very safe way to insert data in a database.
It's vulnerable to SQL injection. Which is probably what's happening.
You probably have a ' in your inserted data somewhere, which ends the query too soon.
You should check this article out, it'll show you how to use prepared statements, or other ways to protect your query.
https://www.owasp.org/index.php/SQL_Injection_Prevention_Cheat_Sheet
If you're curious you could also look into Hibernate. With a bit of configuration, it can safely persist your entities without having to write lengthy queries yourself
http://docs.jboss.org/hibernate/orm/4.2/quickstart/en-US/html/