Yo guys. The problem I'm facing is pretty weird..
I am creating a table at first, then trying to put data on it, but for somereason something is ticking off. It says
[SQLITE_ERROR] SQL error or missing database (no such table: Name)
Aaand here's my basic code..
try{
Class.forName("org.sqlite.JDBC");
conni = DriverManager.getConnection("jdbc:sqlite://C://Users//Asus//Dropbox//TireShop.sqlite");
stmt = conni.createStatement();
String sql = "CREATE TABLE " + project.getText() + " (Id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL , Name TEXT, One TEXT, Two TEXT)";
stmt.executeUpdate(sql);
stmt.close();
conni.close();
}catch (Exception e){
System.err.println( e.getClass().getName() + ": " + e.getMessage() );
System.exit(0);
}
try{
Class.forName("org.sqlite.JDBC");
conni = DriverManager.getConnection("jdbc:sqlite://C://Users//Asus//Dropbox//TireShop.sqlite");
String query1 = "insert into Name (Name) values(?)";
PreparedStatement pst = conni.prepareStatement(query1);
pst.setString(1, project.getText());
pst.execute();
pst.close();
conni.close();
}catch(Exception e){
System.err.println( e.getClass().getName() + ": " + e.getMessage() );
System.exit(0);
}
try{
Class.forName("org.sqlite.JDBC");
conni = DriverManager.getConnection("jdbc:sqlite://C://Users//Asus//Dropbox//TireShop.sqlite");
String query1 = "insert into " + project.getText() + "(Name, One, Two) values(?,?,?)";
PreparedStatement pst = conni.prepareStatement(query1);
pst.setString(1, project.getText());
pst.setString(2, textField_one.getText());
pst.setString(3, textFieldtwo.getText());
pst.execute();
pst.close();
conni.close();
}catch(Exception e){
System.err.println( e.getClass().getName() + ": " + e.getMessage() );
System.exit(0);
JOptionPane.showMessageDialog(null, "Thank you");
Thank you for the help! I really can understand... I guess the table is not being created at all, but it actually worked once. So It gets me even more confused o.o
Name is a MySql reserved keyword. Rename the table to something else.
Please encase your fieldnames with " to escape them.
String sql = "CREATE TABLE \"" + project.getText() + "\" (\"Id\" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL , \"Name\" TEXT, \"One\" TEXT, \"Two\" TEXT)";
String query1 = "insert into \"Name\" (\"Name\") values(?)";
String query1 = "insert into \"" + project.getText() + "\" (\"Name\", \"One\", \"Two\") values(?,?,?)";
Also... I'm assuming you've patched together these code snippets from various points in your code..
But i advice you to set up a SINGULAR database connection in your code and to reuse that connection throughout your application.
Something along the lines of:
public class MyApp {
public static Connection DB;
public void initDatabase() {
try {
MyApp.DB = DriverManager.getConnection("jdbc:sqlite://C://Users//Asus//Dropbox//TireShop.sqlite");
}
catch(Exception ex) {
}
}
public static void main(String args[]) {
MyApp app = new MyApp();
app.initDatabase();
}
}
Related
I am working on Java GUI application which connects to SQL database on localhost (I use XAMPP). When I change some entry, for example Age, I click on "Save changes", it is saved and changes are done in SQL database, but when I click on ">" or "<" to view next or previous person and then go back to the person, where I did changes, every entry is without changes in its initial state. But when I close the application and reopen it, all the changes which I made are done. This is part of the code where is mistake, I think. Thank you.
private void jButtonSaveChangesActionPerformed(java.awt.event.ActionEvent evt) {
try {
Statement stmt = con.createStatement();
try {
String query1 = "UPDATE list1 SET " +
"name ='" + jTextFieldName.getText() + "', " +
"surname ='" + jTextFieldSurname.getText() + "', " +
"age ='" + jTextFieldAge.getText() + "' " +
"WHERE ID = " + jLabelActualID.getText();
stmt.executeUpdate(query1);
} catch (Exception e) {
System.err.println(e);
}
} catch (Exception e) {
System.err.println(e);
}
}
Picture of application:
You are not closing, which can be done more safe and automatically with try-with-resources.
This means a commit might not have happened yet. There is an autocommit setting too.
String query1 = "UPDATE list1 SET " +
"name = ?, " +
"surname = ?, " +
"age = ? " +
"WHERE ID = ?";
try (PreparedStatement stmt = con.prepareStatement(query1)) { // Closes stmt.
stmt.setString(1, jTextFieldName.getText());
stmt.setString(2, jTextFieldSurname.getText());
stmt.setInt(3, Integer.parseInt(jTextFieldAge.getText()));
stmt.setString(4, jLabelActualID.getText());
int updateCount = stmt.executeUpdate();
} catch (SQLException | NumberFormatException e) {
System.err.println(e);
}
The same may hold (or may not hold) for the SQL connection.
Also one should use a PreparedStatement for security (SQL injection) and type safeness / escaping of backslash, quote in strings. As you see it is even more readable.
Another case is a second application accessing the database: it can use its own cache, thereby be a bit outdated.
I have a java derby database, I can write to and read from the database.
I am having trouble:
Making it so that the text that the user enters into the text field, is then incorporated into the database query to determine the results displayed.
I tried it this way, the results were, if I click the search button, it will return the info/query into the "run" screen, not actually incorporating the user input into the query tho, I have to do that in the code, by replacing the abc to the number in the database.
Do I have to create some kind of command line argument? set the variable differently? Can I just replace the query info where the database info goes with a variable like how I tried in the upcoming example?
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
String abc = jTextField1.getText();
String data = "jdbc:derby://localhost:1527/sample";
try (
Connection conn = DriverManager.getConnection(
data, "app", "app");
Statement st = conn.createStatement()) {
Class.forName("org.apache.derby.jdbc.ClientDriver");
ResultSet rec = st.executeQuery(
"select ROW1, ROW2, ROW3, ROW4, ROW5 from APP.NAME1 "
+ "where (ROW4 = 'abc')");
while (rec.next()) {
System.out.println("ROW1:\t"
+ rec.getString(1));
System.out.println("ROW2:\t" + rec.getString(2));
System.out.println("ROW3:\t" + rec.getString(3));
System.out.println("ROW4:\t" + rec.getString(4));
System.out.println("ROW5:\t" + rec.getString(5));
System.out.println();
}
st.close();
} catch (SQLException s) {
System.out.println("SQL Error: " + s.toString() + " "
+ s.getErrorCode() + " " + s.getSQLState());
} catch (Exception e) {
System.out.println("Error: " + e.toString()
+ e.getMessage());
}
}
private void jTextField1ActionPerformed(java.awt.event.ActionEvent evt) {
}
You are not setting the variable correctly. Instead of setting the ROW4 to 'abc' you need to set the variable. Try this.
"select ROW1, ROW2, ROW3, ROW4, ROW5 from APP.NAME1 " + "where (ROW4 = '"+abc+"')"
Its always better to use preparedStatement. this will avoid lot of problem related to SQL Injection.
String selectSQL = "select ROW1, ROW2, ROW3, ROW4, ROW5 from APP.NAME1 where ROW4 = ?";
PreparedStatement preparedStatement = dbConnection.prepareStatement(selectSQL);
preparedStatement.setString(1, abc);
ResultSet rs = preparedStatement.executeQuery(selectSQL );
I am trying to complete my Java Code to execute a SELECT Query that will write the Results into Sysout.
Here is my Code:
public void PullFromDB() {
Connection c = null;
Statement stmt = null;
try {
Class.forName("org.sqlite.JDBC");
c = DriverManager.getConnection("jdbc:sqlite:test.db");
c.setAutoCommit(false);
String sql = "SELECT * FROM " + Name + ";";
stmt = c.createStatement();
ResultSet rs = stmt.executeQuery(sql);
System.out.println(sql);
while (rs.next()) {
Integer ID = rs.getInt("id");
System.out.println("ID = " + ID.toString());
String entry = rs.getString(Properties.get(j));
System.out.println(Properties.get(j) + "=" + entry);
j++;
}
rs.close();
stmt.close();
c.close();
} catch (Exception e) {
System.err.println(e.getClass().getName() + ": " + e.getMessage());
System.exit(0);
}
}
When I sysout my SQL Query it looks like this:
CREATE TABLE IF NOT EXISTS Cars(ID INTEGER PRIMARY KEY AUTOINCREMENT,AnzSitze TEXT,Marke TEXT,Pferdestärke TEXT);
INSERT INTO Cars(AnzSitze,Marke,Pferdestärke) VALUES('vier','Audi','420');
SELECT * FROM Cars;
Those are just some examples I put in.
maybe create and propabley insert has failed, i see none-ascii characters in filed name Pferdestärke try to use valid names
check this
Permitted characters in unquoted identifiers:
ASCII: [0-9,a-z,A-Z$_] (basic Latin letters, digits 0-9, dollar,
underscore)
Extended: U+0080 .. U+FFFF
so replace the filed name Pferdestärke to Pferdestarke in all qrys and try again
my java servlet init method fails to create mysql tables - I'd like to know why. When I log on to mysql directly and create the tables life is beautiful, when I delete the tables and run the servlet - no tables, servlet throws an exception (haven't quite dug that up yet).The code looks like this:
package ...;
import ... // quite a bit
#WebServlet("/MyClass")
public class MyClass extends HttpServlet {
public void init() throws ServletException {
try { Foo foo = Foo.getInstance();
foo.createTables();
} catch (Exception e) {
throw new ServletException("Error creating tables", e);
}
}
... // more MyClass stuff
}
//Foo is a singleton that looks like this:
package ...;
import ... // quite a bit
public class Foo {
public static final Foo INSTANCE = new Foo();
public static Foo getInstance() {
return INSTANCE;
}
... // more Foo stuff, then
public void createTables(){
try {
// first establish a connection
Connection connection = Foo.getInstance().getConnection(); // get connection est.
// est. connection to dbase - works well once the tables are set up
//Create a query.
Statement stmt = connection.createStatement();
String query = "CREATE TABLE IF NOT EXISTS survey (uuid_Survey VARCHAR(36) NOT NULL, "+
"top VARCHAR(40), " +
" likert VARCHAR(40), "+
" numerical VARCHAR(40), "+
" open VARCHAR(40), " +
" KEY ix_survey_uuid (uuid_Survey), "+
" PRIMARY KEY (uuid_Survey))";
ResultSet rs = stmt.executeQuery( query );
query = "CREATE TABLE IF NOT EXISTS result (" +
"uuid_Survey VARCHAR(36) NOT NULL, "+
"remoteAddress VARCHAR(15) NOT NULL, " +
"currentTime BIGINT NOT NULL, "+
" likert VARCHAR(40),"+
" numerical DOUBLE, " +
" open VARCHAR(40), "+
" PRIMARY KEY (uuid_Survey, remoteAddress, currentTime),"+
"FOREIGN KEY ix_survey_uuid (uuid_Survey) REFERENCES survey (uuid_Survey))" ;
rs = stmt.executeQuery( query );
connection.close();
} catch (Exception e) {
System.err.println("Error creating tables: " + e);
}
}
You cannot use stmt.executeQuery( query );
As the Doc says-
ResultSet#executeQuery(String sql) - This method executes the given SQL statement, which returns a single ResultSet object. where sql - an SQL statement to be sent to the database, typically a static SQL SELECT statement
You might want to use execute() instead
Like stmt.execute(query);
or
String query = "CREATE TABLE IF NOT EXISTS survey (uuid_Survey VARCHAR(36) NOT NULL,"+
"top VARCHAR(40), " +
" likert VARCHAR(40), "+
" numerical VARCHAR(40), "+
" open VARCHAR(40), " +
" KEY ix_survey_uuid (uuid_Survey), "+
" PRIMARY KEY (uuid_Survey))";
PreparedStatement statement = conn.prepareStatement(query);
int count = statement.executeUpdate();
if(count>=0){
System.out.println("Successfully created.");
}
I have a problem to insert a new row of data into a table I created via JDBC. It throws SQLException after the ExecuteUpdate() line.
Below I provide a code which created the DB and the Table in this DB. The second part has the code which is supposed to insert values into row in a PatientsData table.
public class DbSetUp {
private static Connection con;
private static String mySqlString = "CREATE TABLE PatientsData" +
"(id INTEGER PRIMARY KEY," +
"fname VARCHAR(30) NOT NULL," +
"lname VARCHAR(30) NOT NULL," +
"sex VARCHAR(1) NOT NULL," +
"insurance VARCHAR(1) NOT NULL," +
"profession VARCHAR(30) NOT NULL)";
//private boolean end;
private static String strTemp = "CREATE TABLE PatientsTemp" +
"(id INTEGER PRIMARY KEY," +
"name VARCHAR(256) NOT NULL," +
"date DATE NOT NULL," +
"temp NUMERIC NOT NULL)";
public static void main(String[] args) {
try {
Class.forName("org.apache.derby.jdbc.EmbeddedDriver");
} catch (ClassNotFoundException e) {
System.out.println("Driver not found");
e.printStackTrace();
}
try {
con = DriverManager.getConnection("jdbc:derby:PatientDb;create=true");
} catch (SQLException e) {
System.out.println("Db not found");
e.printStackTrace();
}
Statement statement = null;
try{
statement = con.createStatement();
statement.execute(mySqlString);
statement.execute(strTemp);
} catch(SQLException ex){
ex.printStackTrace();
}
}
The above code works fine throwing no exceptions. I assume that both tables have been created and the DB exists:)
Not the part which is supposed to insert data:
public Patient createNewPatient(int id, String fname, String lname,
String sex, String insurance, String profession) {
try {
DriverManager.registerDriver(new org.apache.derby.jdbc.EmbeddedDriver());
} catch (SQLException e1) {
System.out.println("to na poczatku");
e1.printStackTrace();
}
try{
con = DriverManager.getConnection("jdbc:derby:PatientDb");
PreparedStatement ps = con.prepareStatement("INSERT INTO PatientsData VALUES(?,?,?,?,?,?)");
System.out.println("Prepared Statement");
ps.setInt(1, id);
System.out.println("set int id");
ps.setString(2, fname);
ps.setString(3,lname);
ps.setString(4,sex);
ps.setString(5, insurance);
ps.setString(6,profession);
System.out.println("set string profession");
result = ps.executeUpdate();
System.out.println(result);
return new Patient(id,fname,lname,sex,insurance,profession);
//System.out.println("set string profession");
} catch(SQLException e){
System.out.println("SQL exception");
return null;
}
}
The line: result = ps.executeUpdate(); throws SQLException, I have no idea where is the mistake. I have added derby.jar into my build path.
your SQL statement is wrong
INSERT INTO PatientsData VALUES(?,?,?,?,?,?)
neets to be
INSERT INTO PatientsData(columnname1,columname2...) VALUES(?,?,?,?,?,?)
i suspect...didnt really read about the functionality but looks fine.
Ah misread ... its a Derby query... my format is from MS SQL.. so.. donno if its answer
The problem would be you are trying to insert duplicate value in ID column
Ensure that you are generating unique value for ID.