When I put my data onto MSAccess, it goes there with dollar signs before it. Here is my relevant code:
try (Connection conn = DriverManager.getConnection(
"jdbc:ucanaccess://" + dbPath
+ ";newdatabaseversion=V2010"
)) {
DatabaseMetaData dmd = conn.getMetaData();
try (ResultSet rs = dmd.getTables(null, null, tableName, new String[] { "TABLE" })) {
try (Statement s = conn.createStatement()) {
s.executeUpdate("CREATE TABLE " + tableName +" (Row COUNTER PRIMARY KEY, aColumn NUMBER , bColumn NUMBER)");
System.out.println("Table " + tableName + " created.");
}
}
conn.close();
}
}
catch (Exception f){
f.printStackTrace();
}
...
try{
statement.execute("DISABLE AUTOINCREMENT ON " + tableName );
statement.executeUpdate("INSERT INTO " + tableName
+ " ( Row, aColumn, bColumn)"
+ " VALUES ( "+(i+1)+", "+a+", "+b+")");
System.out.println("row " + i);
}
catch (Exception f ){
f.printStackTrace();
}
When I input 1, 2, 3, and 4 as my values, the graph displays the following: https://puu.sh/weGuX/3000d456bb.png
Any suggestions as to why this would be would be much appreciated, thank you.
NUMBER in UCanAccess DDL maps to the Currency field type in Access, while in the Access UI the default "Number" type is "Long Integer". If you want to create a long integer column then use the DDL keyword LONG.
Related
if (Baglan() == false) { return false; }
try{
String generatedColumns[] = {"ID","TAHSILATNO"};
String sSql = "Declare nId number := 0;" +
" nKey number := 0;" +
" BEGIN" +
" Select Nvl(Max(Id),0) + 1 INTO nId From bvktahsilatno;" +
" INSERT INTO bvktahsilatno (id, yili, tahsilatno ) VALUES( nId, 2018, 53);" +
" EXCEPTION " +
" WHEN DUP_VAL_ON_INDEX THEN" +
" Select Nvl(Max(Id),0) + 1 INTO nId From bvktahsilatno;" +
" Select Nvl(Max(tahsilatno),0) + 1 INTO nKey From bvktahsilatno WHERE Yili = 2018;" +
" INSERT INTO bvktahsilatno (id, yili, tahsilatno ) VALUES( nId, 2018, nKey);" +
"END;";
//VtStatement = VtConnection.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
//VtStatement.execute(pSql);
//PreparedStatement VtStatement = VtConnection.prepareStatement( sSql, Statement.RETURN_GENERATED_KEYS );
//PreparedStatement VtStatement = VtConnection.prepareStatement( sSql, generatedColumns );
PreparedStatement VtStatement = VtConnection.prepareStatement( sSql, Statement.RETURN_GENERATED_KEYS);
System.out.println("oracle cumle : " + sSql);
int nAdet = VtStatement.executeUpdate();
System.out.println("Hatayok/Adet : " + nAdet);
ResultSet rs = VtStatement.getGeneratedKeys();
int id=0;
while (rs.next()) {
id = rs.getInt(1);
}
System.out.println("Oracle Inserted ID -" + id); // display inserted record
return true;
} catch (SQLException e) {
return false;
}
I want to ask a question about retrieving created keys on Oracle Db after insert query. My code is as above but generated keys values are not showed on the terminal. How can i get generated column values without creating sequence ? Many form pages say that it is possible as using sequence for id or other column. Also id is primary key, tahsilatno is unique index. I can overcome this problem?
Thank you for your helping from now
I'm trying to create a SQLite for my game, and its working fine until I try to put some variables in the table HighScores.
If I try to put a variable it only works if I delete the "NOT NULL".
public void SQLite(){
Connection c = null;
Statement stmt = null;
try {
Class.forName("org.sqlite.JDBC");
c = DriverManager.getConnection("jdbc:sqlite:test.db");
stmt = c.createStatement();
String sql = "CREATE TABLE HighScores " +
"(ID INT PRIMARY KEY NOT NULL," +
" POINTS INT NOT NULL, " +
" NAME CHAR(50) NOT NULL, " +
" TIME INT NOT NULL, " +
" LEVEL INT NOT NULL)";
stmt.executeUpdate(sql);
c.setAutoCommit(false);
System.out.println("Opened database successfully");
stmt = c.createStatement();
String sql2 = "INSERT INTO HIGHSCORES (ID,POINTS,NAME,TIME,LEVEL) " +
"VALUES (1, ?, 'rodrigo', 99, 1 );";
PreparedStatement ps = c.prepareStatement(sql2);
ps.setInt(1, 5);
stmt.executeUpdate(sql2);
stmt.close();
c.commit();
c.close();
} catch ( Exception e ) {
System.err.println( e.getClass().getName() + ": " + e.getMessage() );
System.exit(0);
}
}
Opened database successfully.
java.sql.SQLException: NOT NULL constraint failed: HighScores.POINTS
You are calling executeUpdate on stmt instead of the prepared statement. Since sql2 does not have any value for POINTS, it try to insert null hence the exception.
Change :
stmt.executeUpdate(sql2);
to
ps.executeUpdate();
I am trying to create a generic method that can add an entry into a SQLite database, using Eclipse and Java.
When the table name is hardcoded it works fine, but when I try to pass in the table name as a string it is giving me a nullPointerException.
below is the method that creates that table:
public static void Table()
{
Connection c = null;
Statement stmt = null;
try {
Class.forName("org.sqlite.JDBC");
c = DriverManager.getConnection("jdbc:sqlite:test.db");
System.out.println("Opened database successfully");
stmt = c.createStatement();
String sql = "CREATE TABLE IF NOT EXISTS COMPANY " +
"(ID INT PRIMARY KEY NOT NULL," +
" NAME TEXT NOT NULL, " +
" AGE INT NOT NULL, " +
" ADDRESS TEXT, " +
" SALARY REAL)";
stmt.executeUpdate(sql);
stmt.close();
c.close();
} catch ( Exception e ) {
System.err.println( e.getClass().getName() + ": " + e.getMessage() );
System.exit(0);
}
System.out.println("Table created successfully");
}
and here is the method that inserts an entry into the created table. I want to pass in the table name through the method rather than hard coding it:
public static void Insert(String table, int id, String name, int age, String address, String salary)
{
Connection c = null;
PreparedStatement pstmt = null;
try {
Class.forName("org.sqlite.JDBC");
c = DriverManager.getConnection("jdbc:sqlite:test.db");
c.setAutoCommit(false);
System.out.println("Opened database successfully");
String query="INSERT INTO "+table+" (ID,NAME,AGE,ADDRESS,SALARY) VALUES (?,?,?,?,?)";
PreparedStatement stmt = c.prepareStatement(query);
pstmt.setInt(1,id);
pstmt.setString(2,name);
pstmt.setInt(3, age);
pstmt.setString(4, address);
pstmt.setString(5, salary);
pstmt.executeUpdate();
pstmt.close();
c.commit();
c.close();
} catch ( Exception e ) {
System.err.println( e.getClass().getName() + ": " + e.getMessage() );
System.exit(0);
}
System.out.println("Records created successfully");
}
You have small mistake
just you have created two different PreparedStatement object
So change
PreparedStatement stmt = c.prepareStatement(query);
to
pstmt = c.prepareStatement(query);
I am trying to insert data into a SQLite database from a blackberry. When I call the screen I also call a method to create the database:
boolean sdCardPresent = false;
public static Database sqliteDB;
URI uri;
public void createdatabase()
{
try{
Enumeration e = FileSystemRegistry.listRoots();
root = (String)e.nextElement();
Dialog.inform(root);
if(root.equalsIgnoreCase("sdcard/"))
{
sdCardPresent = true;
}
if(!sdCardPresent)
{
Dialog.inform("O seu dispositivo nao suporta este compartimento sem cartao de memoria, verifique se existe um SD card no seu dispositivo.");
UiApplication.getUiApplication().pushScreen(new Tab_Main());
}else{
uri = URI.create(
"file:///SDCard/Databases/MBA.db");
sqliteDB = DatabaseFactory.openOrCreate(uri);
sqliteDB = DatabaseFactory.open(uri);
Statement st = sqliteDB.createStatement("DROP TABLE IF EXISTS atms;CREATE TABLE atms " +
"( id INTEGER PRIMARY KEY AUTOINCREMENT ," +
" localizacao TEXT, " +
" mapa TEXT ," +
" foto1 TEXT ," +
" foto2 TEXT," +
" zona TEXT);" +
"" +
"DROP TABLE IF EXISTS balcoes;CREATE TABLE balcoes " +
"( id INTEGER PRIMARY KEY AUTOINCREMENT ," +
" localizacao TEXT, " +
" mapa TEXT ," +
" foto1 TEXT ," +
" foto2 TEXT," +
" zona TEXT);" +
"" +
"DROP TABLE IF EXISTS contactos;CREATE TABLE contactos " +
"( id INTEGER PRIMARY KEY AUTOINCREMENT ," +
" nome TEXT, " +
" numero_conta INTEGER);") ;
st.prepare();
st.execute();
st.close();
sqliteDB.close();
Dialog.inform("Status: Database was successfully created.");
//}
} catch (Exception e){
System.out.println(e.getMessage());
Dialog.inform("\n "+e);
//UiApplication.getUiApplication().popScreen(Screen);
}
}
After that I use some Editfields and other components to get the values. I call the method to insert the parameters and send the query:
public void insert_update(String query) {
try {
sqliteDB = DatabaseFactory.openOrCreate(uri);
Statement st = sqliteDB.createStatement(query);
//Statement statement = _db.createStatement(query);
st.prepare();
st.execute();
st.close();
Dialog.inform("Adicionado com sucesso!!!");
}
catch ( Exception e ) {
Dialog.inform(e+"");
}
}
For example when I call it with the query = "insert into contactos values (null,"a","1"); I get an exception. SQL logic error or missing database.
Try dropping the quotes around the third column value.
INSERT INTO contactos VALUES (null,"a", 1);
It's defined as an INTEGER.
numero_conta INTEGER
EDIT :
System.out.println(uri); // check if null, or different
if (uri == null) {
uri = URI.create(
"file:///SDCard/Databases/MBA.db");
}
sqliteDB = DatabaseFactory.openOrCreate(uri);
sqliteDB = DatabaseFactory.open(uri); // open again
Statement st = sqliteDB.createStatement(query);
I'm new to connecting java with a mysql database. What's wrong with my query here:
PreparedStatement statement = conn.prepareStatement("SELECT * FROM q_table, choices, answers WHERE q_table.QID='" + number_input + "' AND choices.CID='" + number_input + "' AND answers.AID='" + number_input + "'");
In your statement " ... q_table.QID='" + number_input + "' AND ... the variable number_input is enclosed in a single quote ('). This is used for string lieterals. If you remove the single quote it should work:
String prest= "SELECT * FROM q_table, choices, answers WHERE questions.QID=? AND choices.CID=? AND answers.AID=?";
prest.setInt(1,1980);
prest.setInt(2,2004);
.
.
ResultSet rs = prest.executeQuery();
while (rs.next()){
String mov_name = rs.getString(1);
int mov_year = rs.getInt(2);
count++;
System.out.println(mov_name + "\t" + "- " + mov_year);
}
System.out.println("Number of records: " + count);
prest.close();
con.close();
Well, the first problem is that you're opening yourself up to a SQL injection attack by including values directly in your SQL. Use a parameterized query instead.
Now we can't really tell what's wrong beyond that, although the fact that you're quoting a number seems suspicious, as does the fact that you're using the same value for a question ID, a choice ID and an answer ID. That seems unlikely to be appropriate.
If you could give us more information about what's happening vs what you expected to happen, that would really help.
When you use prepared statements, you can't set the values there.
You have to first prepare the statement using question marks and then set the parameters later.
Here is an example:
public void updateCoffeeSales(HashMap<String, Integer> salesForWeek) throws SQLException {
PreparedStatement updateSales = null;
PreparedStatement updateTotal = null;
String updateString = "update " + dbName + ".COFFEES " +
"set SALES = ? where COF_NAME = ?";
String updateStatement = "update " + dbName + ".COFFEES " +
"set TOTAL = TOTAL + ? where COF_NAME = ?";
try {
con.setAutoCommit(false);
updateSales = con.prepareStatement(updateString);
updateTotal = con.prepareStatement(updateStatement);
for (Map.Entry<String, Integer> e : salesForWeek.entrySet()) {
updateSales.setInt(1, e.getValue().intValue());
updateSales.setString(2, e.getKey());
updateSales.executeUpdate();
updateTotal.setInt(1, e.getValue().intValue());
updateTotal.setString(2, e.getKey());
updateTotal.executeUpdate();
con.commit();
}
} catch (SQLException e ) {
JDBCTutorialUtilities.printSQLException(e);
if (con != null) {
try {
System.err.print("Transaction is being rolled back");
con.rollback();
} catch(SQLException excep) {
JDBCTutorialUtilities.printSQLException(excep);
}
}
} finally {
updateSales.close();
updateTotal.close();
con.setAutoCommit(true);
}
}
SELECT * FROM q_table, choices, answers WHERE q_table.QID='" + number_input + "' AND choices.CID='" + number_input + "' AND answers.AID='" + number_input + "'"
or
SELECT * FROM questions, choices, answers WHERE questions.QID='" + number_input + "' AND choices.CID='" + number_input + "' AND answers.AID='" + number_input + "'"
That is not a proper prepareStatement. It's a concatenated query that will only lead you to sql injection horrors. Look here