Cannot insert data into a table in db using jdbc - java

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.

Related

MySQL table not visible in Workbench

I executed the below code to create a table USER and everything looks fine since when I try to execute it again, I get the error "Table 'USER' already exists".
public static void main(String[] args) throws SQLException, ClassNotFoundException {
sqlDB mysqlConnect = new sqlDB();
Statement stmt = mysqlConnect.connect().createStatement();
String sql = "CREATE TABLE USER " +
"(id INTEGER not NULL, " +
" first VARCHAR(255), " +
" last VARCHAR(255), " +
" PRIMARY KEY ( id ))";
try {
stmt.executeUpdate(sql);
PreparedStatement statement = mysqlConnect.connect().prepareStatement(sql);
} catch (SQLException e) {
e.printStackTrace();
} finally {
mysqlConnect.disconnect();
}
}
My question is why don't I see this table in MySQL Workbench?
I checked the section 'Schemas' but there I have only 1 db 'sys' which is not the one I created.
User is a mysql system table;
You can create a new db and create the table new db.Tablename;

Failed to create table with SQLite

I'm trying to create a table with a list of names in it. This outputs:
"Failed to create table_name"
It was working before, I'm using Netbeans IDE with SQLite 3.7.2. I've also tried executing statements on the database which works fine. But it won't work through the Java code below
class DatabaseHelper{
public void addToDb(String tbname, List<String> name){
try {
String url = "jdbc:sqlite:D:/names.db";
Class.forName("org.sqlite.JDBC");
try(Connection conn = DriverManager.getConnection(url);
Statement stmt = conn.createStatement();){
stmt.execute("CREATE TABLE IF NOT EXISTS " + tbname + "(id integer PRIMARY KEY AUTOINCREMENT,"
+ "name text NOT NULL)");
name.forEach((s) -> {
try{
stmt.execute("INSERT INTO " + tbname + "(name) VALUES('" + s + "')");
}catch(SQLException e){
e.printStackTrace();
}
});
System.out.println("Finished");
}catch(SQLException e){
e.printStackTrace();
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
EDIT : It does works, only takes to refresh it. No actual problems it seems
Try to create your table with a database name like this :
String query = "CREATE TABLE IF NOT EXISTS databasename." + tbname +
" (id integer PRIMARY KEY AUTOINCREMENT, name text NOT NULL)";
If your database already contain schema then create your table with schema name like this :
CREATE TABLE [IF NOT EXISTS] [schema_name].table_name (
so :
String query = "CREATE TABLE IF NOT EXISTS sch_name." + tbname +
" (id integer PRIMARY KEY AUTOINCREMENT, name text NOT NULL)";
You can learn more here : SQLite Create Table
Ooops this is logic
This error is logic it return false all the time, if you try st.executeUpdate(q) and your query is success it will return 0 because CREATE TABLE does not return any thing for that you get negative result all the time, not like Insert or Update it return a result when you execute your statement, so i suggest to change your code to this :
boolean created;
try {
q = "CREATE TABLE ...";
Statement st = connection.createStatement();
//you can use
System.out.println(st.executeUpdate(q));
//or
System.out.println(st.execute(q));
created = true;
} catch (SQLException e) {
created = false;
}
//now you can check if your table is created or not
if(created){
System.out.println("Table created with sucess");
}else{
System.out.println("Faild to create table");
}
Hope this work with you.
if(stmt.execute("CREATE TABLE IF NOT EXISTS " + tbname + ";"+"CREATE TABLE "+ tbname + "(id integer PRIMARY KEY AUTOINCREMENT,"
+ "name text NOT NULL)"))
or can you give the exception that was raised

No such Table Sqlite JDBC

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();
}
}

SQL error in java code "Column count doesn't match value count at row 1"

I have a problem with my program. When I try to write to my database (in MySQL) I get this error "Column count doesn't match value count at row 1"
This is my code:
public void registreerNieuwSpelbord(String spelnaam, String mapcode) {
try (Connection connectie = DriverManager.getConnection(Connectie.JDBC_URL)) {
Statement stmt = connectie.createStatement();
String schrijfSpelbordWeg = "INSERT INTO spelbord(Mapcode, spel_Spelnaam) values('" + mapcode + "," + spelnaam + "')";
stmt.executeUpdate(schrijfSpelbordWeg);
} catch (SQLException ex) {
throw new RuntimeException(ex);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
note: there is also a 3th column with an ID that automatically gives a number
You have two columns listed in the insert, but only one value.
Try this:
String schrijfSpelbordWeg = "INSERT INTO spelbord(Mapcode, spel_Spelnaam) values('" + mapcode + "','" + spelnaam + "')";
You should always use a PreparedStatement and bind variables when dealing with SQL that takes input parameters. This way, you're eliminating the chance of SQL injection, allowing the DB to re-use/cache your query and sparing yourself from hunting down bugs that are caused by missing a quote around a parameter.
Here's a refactored version that uses parameterized SQL:
public void registreerNieuwSpelbord(String spelnaam, String mapcode) {
String sql = "INSERT INTO spelbord(Mapcode, spel_Spelnaam) values(?, ?)";
try (Connection connectie = DriverManager.getConnection(Connectie.JDBC_URL);
PreparedStatement ps = connectie.prepareStatement(sql);) {
ps.setString(1, mapcode);
ps.setString(2, spelnaam);
ps.executeUpdate();
} catch (SQLException ex) {
throw new RuntimeException(ex);
}
}

servlet init method fails to create mysql tables - why?

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.");
}

Categories