public void createDatabase(){
try {
Class.forName("org.sqlite.JDBC").newInstance();
Connection connection = DriverManager.getConnection("jdbc:sqlite:occDatabase.db");
Statement statement = connection.createStatement();
String sqlStatement = "CREATE TABLE 'Player_Data' (" +
"'userMoney' TEXT," +
"'oysters' TEXT," +
"'clams' TEXT," +
"'cockles' TEXT," +
"'oysterPrice' TEXT," +
"'clamPrice' TEXT," +
"'cocklePrice' TEXT," +
"'oysterMod' TEXT," +
"'clamMod' TEXT," +
"'cockleMod' TEXT," +
"'cartPrice' TEXT," +
"'fishStandPrice' TEXT," +
"'storePrice' TEXT," +
"'superMarketPrice' TEXT," +
"'cartAmount' TEXT," +
"'fishStandAmount' TEXT," +
"'storeAmount' TEXT," +
"'superMarketAmount' TEXT," +
");";
statement.execute(sqlStatement);
connection.commit();
statement.close();
connection.close();
} catch (Exception e){
}
}
public void writeToDatabase(){
try{
clearData();
createDatabase();
Class.forName("org.sqlite.JDBC");
Connection connection = DriverManager.getConnection("jdbc:sqlite:occDatabase.db");
Statement statement = connection.createStatement();
String sqlStatemnt = "INSERT INTO Player_Data(userMoney,oysters,clams,cockles,oysterPrice,clamPrice,cocklePrice,oysterMod,clamMod,cockleMod" +
",cartPrice,fishStandPrice,storePrice,superMarketPrice,cartAmount,fishStandAmount,storeAmount,superMarketAmount) " +
"VALUES('" + MainActivity.userMoney + "', '"+ GatheringSystem.oysters +"', '" + GatheringSystem.clams +"', '" + GatheringSystem.cockles +"'," +
" '" + Modifiers.oysterPrice +"', '" + Modifiers.clamPrice +"', '" + Modifiers.cocklePrice +"', '" + Modifiers.oysterMod +"', '" + Modifiers.clamMod +"', '" + Modifiers.cockleMod +
"', '" + MainActivity.cartPrice +"', '" + MainActivity.fishStandPrice +"', '" + MainActivity.storePrice +"', '" + MainActivity.superMarketPrice +"', '" + MainActivity.cartAmount +"'," +
" '" + MainActivity.fishStandAmount +"', '" + MainActivity.storeAmount +"', '" + MainActivity.superMarketAmount +"')";
statement.execute(sqlStatemnt);
connection.commit();
statement.close();
connection.close();
}catch (Exception e){
}
}
public void readFromDatabase(){
Connection connection = null;
Statement statement = null;
try {
Class.forName("org.sqlite.JDBC").newInstance();
connection = DriverManager.getConnection("jdbc:sqlite:occDatabase.db");
statement = connection.createStatement();
} catch (Exception e){
}
try{
ResultSet resultSet = statement.executeQuery("SELECT * FROM Player_Data");
while (resultSet.next()){
MainActivity.userMoney = Double.parseDouble(resultSet.getString("userMoney"));
MainActivity.cartPrice = Double.parseDouble(resultSet.getString("cartPrice"));
MainActivity.fishStandPrice = Double.parseDouble(resultSet.getString("fishStandPrice"));
MainActivity.storePrice = Double.parseDouble(resultSet.getString("storePrice"));
MainActivity.superMarketPrice = Double.parseDouble(resultSet.getString("superMarketPrice"));
MainActivity.cartAmount = Integer.parseInt(resultSet.getString("cartAmount"));
MainActivity.fishStandAmount = Integer.parseInt(resultSet.getString("fishStandAmount"));
MainActivity.storeAmount = Integer.parseInt(resultSet.getString("storeAmount"));
MainActivity.superMarketAmount = Integer.parseInt(resultSet.getString("superMarketAmount"));
Modifiers.oysterPrice = Double.parseDouble(resultSet.getString("oysterPrice"));
Modifiers.clamPrice = Double.parseDouble(resultSet.getString("clamPrice"));
Modifiers.cocklePrice = Double.parseDouble(resultSet.getString("cocklePrice"));
Modifiers.oysterMod = Double.parseDouble(resultSet.getString("oysterMod"));
Modifiers.clamMod = Double.parseDouble(resultSet.getString("clamMod"));
Modifiers.cockleMod = Double.parseDouble(resultSet.getString("cockleMod"));
GatheringSystem.oysters = Double.parseDouble(resultSet.getString("oysters"));
GatheringSystem.clams = Double.parseDouble(resultSet.getString("clams"));
GatheringSystem.cockles = Double.parseDouble(resultSet.getString("cockles"));
}
resultSet.close();
statement.close();
connection.close();
MainActivity.databaseStarted = true;
} catch (Exception e){
MainActivity.databaseStarted = false;
}
}
}
So I am really new to coding for android and I am trying to save data for my game, so that when I come back on to the game I can read from the files.
At the moment it doesn't seem to be creating a 'database' at all.
Do I need to give it certain permissions? or can it automatically create files on a users phone?
private void databaseMethod(){
database.readFromDatabase();
if(!databaseStarted){
database.createDatabase();
toast = toast.makeText(getApplicationContext(),"Created Database",Toast.LENGTH_SHORT);
toast.show();
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_main);
distThread.setDaemon(true);
distThread.start();
databaseMethod();
File file = new File(getFilesDir(), "occDatebase.db");
}
#Override
protected void onPause() {
super.onPause();
database.writeToDatabase();
toast = toast.makeText(getApplicationContext(),"Game Saved",Toast.LENGTH_SHORT);
toast.show();
}
On creation I check to see if there is already a database, if not it should be creating one.
But it doesnt even seem to be doing that.
Any suggestions?
Thanks.
Android does not have JDBC.
And all the try/except blocks suppress any error messages.
For how to use the Android database framework, see the documentation, or any tutorial.
Related
I'm using sql developer and netbeans when ever i try to insert data into the table this error "sql Command has not properly ended".
This is what i tried.
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
dbconnection db = new dbconnection();
try {
db.connect();
db.stm = db.con.createStatement();
int result = db.stm.executeUpdate(
"insert into payment values'" + txt_paymentid.getText() + "','" + txt_reservation.getText() +"',
" + "'"+txt_fname.getText()+"',
'"+txt_lname.getText()+"' ,'"+txt_roomid.getText()+"' ,'"+txt_rate.getText()+"' ," + " '"+((JTextField)txt_datein.getDateEditor().getUiComponent()).getText()+"' ,"
+ "'"
((JTextField
)txt_dateout.getDateEditor().getUiComponent()).getText() + "'," + "'" + txt_days.getText() + "','" + txt_payment.getText() + "','" + txt_balance.getText() + "'"
);
if (result > 0) {
JOptionPane.showMessageDialog(this, "Data has been saved succesfully");
} else {
JOptionPane.showMessageDialog(this, "no data has been saved");
}
} catch (SQLException e) {
JOptionPane.showMessageDialog(this, e.toString());
}
}
For a start
The sql should be in the ()
executeUpdate()("insert...
->
executeUpdate("insert...)
second it looks like the insert command itself it not valid
insert into table values (' ....
I want to create a java source object in oracle database via JDBC, PreparedStatement. However, in the java source file, there are several question marks. Once I executed it, I faced an error message like below..
java.sql.SQLException: Parameter index out of range (1 > number of parameters, which is 0).
I changed my code to be more understandable.
private void installOS_COMMAND() {
Connection targetDBconn = null;
PreparedStatement pstmt = null;
Statement stmt = null;
try {
String SQL = "create or replace java source named \"FILE_TYPE_JAVA\" as\n"
+ "public class FileType {\n"
+ " public static String getFileTypeOwner(Connection con) throws Exception {\n"
+ " String sFileTypeOwner = null;\n"
+ " CallableStatement stmt = con.prepareCall(\"begin dbms_utility.name_resolve(?,?,?,?,?,?,?,?); end;\");\n"
+ " stmt.setString(1, \"FILE_TYPE\");\n"
+ " stmt.setInt(2, 7);\n"
+ " stmt.registerOutParameter(3, java.sql.Types.VARCHAR);\n"
+ " stmt.registerOutParameter(4, java.sql.Types.VARCHAR);\n"
+ " stmt.registerOutParameter(5, java.sql.Types.VARCHAR);\n"
+ " stmt.registerOutParameter(6, java.sql.Types.VARCHAR);\n"
+ " stmt.registerOutParameter(7, oracle.jdbc.OracleTypes.NUMBER);\n"
+ " stmt.registerOutParameter(8, oracle.jdbc.OracleTypes.NUMBER);\n"
+ " stmt.execute();\n"
+ " sFileTypeOwner = stmt.getString(3);\n"
+ " stmt.close();\n"
+ " return sFileTypeOwner;\n"
+ " }\n"
+ "}";
targetDBconn = globalTargetConn.connect();
pstmt = targetDBconn.prepareStatement(SQL);
pstmt.executeUpdate();
} catch (SQLException ex) { logWriter.writeLogs(logTextArea, LogWriter.ERROR, ex.getMessage());
} finally {
if (pstmt != null ) try {pstmt.close();} catch(SQLException ex) {}
if (targetDBconn != null ) try {targetDBconn.close();} catch(SQLException ex) {}
}
}
Is there someone who can fix this problem?
Don't use prepared statements:
private void installOS_COMMAND() {
Connection targetDBconn = null;
Statement stmt = null;
try {
String SQL = "create or replace java source named \"FILE_TYPE_JAVA\" as\n"
+ "public class FileType {\n"
+ " public static String getFileTypeOwner(Connection con) throws Exception {\n"
+ " String sFileTypeOwner = null;\n"
+ " CallableStatement stmt = con.prepareCall(\"begin dbms_utility.name_resolve(?,?,?,?,?,?,?,?); end;\");\n"
+ " stmt.setString(1, \"FILE_TYPE\");\n"
+ " stmt.setInt(2, 7);\n"
+ " stmt.registerOutParameter(3, java.sql.Types.VARCHAR);\n"
+ " stmt.registerOutParameter(4, java.sql.Types.VARCHAR);\n"
+ " stmt.registerOutParameter(5, java.sql.Types.VARCHAR);\n"
+ " stmt.registerOutParameter(6, java.sql.Types.VARCHAR);\n"
+ " stmt.registerOutParameter(7, oracle.jdbc.OracleTypes.NUMBER);\n"
+ " stmt.registerOutParameter(8, oracle.jdbc.OracleTypes.NUMBER);\n"
+ " stmt.execute();\n"
+ " sFileTypeOwner = stmt.getString(3);\n"
+ " stmt.close();\n"
+ " return sFileTypeOwner;\n"
+ " }\n"
+ "}";
targetDBconn = globalTargetConn.connect();
stmt = targetDBconn.createStatement();
stmt.setEscapeProcessing(false);
stmt.executeUpdate(SQL);
} catch (SQLException ex) { logWriter.writeLogs(logTextArea, LogWriter.ERROR, ex.getMessage());
} finally {
if (targetDBconn != null ) try {targetDBconn.close();} catch(SQLException ex) {}
}
}
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
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
i'm trying to update paradox table from java but i'm getting an Exception
java.sql.SQLException: [Microsoft][ODBC Paradox Driver] Operation must use an updateable query.
java.sql.SQLException: [Microsoft][ODBC Paradox Driver] Operation must use an updateable query.
java.sql.SQLException: [Microsoft][ODBC Paradox Driver] Operation must use an updateable query.
I'm using this code:
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
try {
Connection paradoxCon = paradox.createConnection();
Results res = new Results();
res.getAll();
if (res.allRes.isEmpty()) {
JOptionPane.showMessageDialog(mainPanel, "There are no Finished or Postponed Games!", "Error", JOptionPane.ERROR_MESSAGE);
} else {
int y = res.allRes.size();
for (int x = 0; x < y; x = x + 1) {
try {
if (res.getAll().get(x).Reversed == 0) {
if (res.getAll().get(x).Status.equals("Fin")) {
String sql = "UPDATE Kvote SET _45_d = '" + res.getAll().get(x).HThome + "', _45_g = '" + res.getAll().get(x).HTaway + "', _90_d= '" + res.getAll().get(x).FThome + "', _90_g = '" + res.getAll().get(x).FTaway + "', Ok='Y' WHERE Kolo = '" + res.getAll().get(x).tRound + "' AND Sifra='" + res.getAll().get(x).TID + "'";
PreparedStatement ps = paradoxCon.prepareStatement(sql);
ps.executeUpdate();
}
if (res.getAll().get(x).Status.equals("Post")) {
String sql = "UPDATE Kvote SET _45_d = '" + res.getAll().get(x).HThome + "', _45_g = '" + res.getAll().get(x).HTaway + "', _90_d= '" + res.getAll().get(x).FThome + "', _90_g = '" + res.getAll().get(x).FTaway + "', Ok='O' WHERE Kolo = '" + res.getAll().get(x).tRound + "' AND Sifra='" + res.getAll().get(x).TID + "'";
PreparedStatement ps = paradoxCon.prepareStatement(sql);
ps.executeUpdate();
}
}
if (res.getAll().get(x).Reversed == 1) {
if (res.getAll().get(x).Status.equals("Fin")) {
String sql = "UPDATE Kvote SET _45_d = '" + res.getAll().get(x).HTaway + "', _45_g = '" + res.getAll().get(x).HThome + "', _90_d= '" + res.getAll().get(x).FTaway + "', _90_g = '" + res.getAll().get(x).FThome + "', Ok='Y' WHERE Kolo = '" + res.getAll().get(x).tRound + "' AND Sifra='" + res.getAll().get(x).TID + "'";
PreparedStatement ps = paradoxCon.prepareStatement(sql);
ps.executeUpdate();
}
if (res.getAll().get(x).Status.equals("Post")) {
String sql = "UPDATE Kvote SET _45_d = '" + res.getAll().get(x).HTaway + "', _45_g = '" + res.getAll().get(x).HThome + "', _90_d= '" + res.getAll().get(x).FTaway + "', _90_g = '" + res.getAll().get(x).FThome + "', Ok='O' WHERE Kolo = '" + res.getAll().get(x).tRound + "' AND Sifra='" + res.getAll().get(x).TID + "'";
PreparedStatement ps = paradoxCon.prepareStatement(sql);
ps.executeUpdate();
}
}
} catch (Exception ex) {
System.out.println(ex);
}
}
}
res.getAll().clear();
} catch (ParseException ex) {
Logger.getLogger(AutoResultsImporterView.class.getName()).log(Level.SEVERE, null, ex);
}
}
I Solve the problem using INTERSOLV 3.11 32-BIT ParadoxFile (*.db) driver
I created an System DSN Data Source Using this driver and connect to this Data Source