MySQL table not visible in Workbench - java

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;

Related

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

H2 Embedded Database tables not shown in Intellij Database Client

I'm learning how to implement a database into a music player application, and decided to use the embedded H2 database for my implementation.
public class H2EmbeddedDB {
public H2EmbeddedDB() {
try {
Class.forName("org.h2.Driver");
Connection conn = DriverManager.getConnection("jdbc:h2:~/data/musicAppDB", "sa", "");
Statement st = conn.createStatement();
/*
String createTableSQL = "CREATE TABLE PLAYLISTS " +
"(playlistID INTEGER not NULL, " +
" playlistName VARCHAR(255), " +
" musicToContinuePath VARCHAR(255), " +
" durationToContinue INTEGER)";
st.execute(createTableSQL);
*/
String sql = "INSERT INTO PLAYLISTS " + "VALUES (123456789, 'Zara', 'C:\\Music', 18)";
st.executeUpdate(sql);
ResultSet rs;
rs = st.executeQuery("select * from playlists");
while (rs.next()) {
System.out.println(rs.getString("playlistName"));
}
conn.close();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
Just a simple test class, I commented out the create table after the table is created. Everything works fine, the application prints out 'Zara' like it should, but I cannot find the table in the Intellij Database Tool.
[How I'm importing the database]
https://i.gyazo.com/e2c1360729d53f837ffe3195290db7fa.png
[Not showing anything in the DB]
https://gyazo.com/4ddc9cea065bd928471aff0805130f73
I know where it is storing the database, it's in my user folder/data, and I've tried putting the absolute path to it when connecting with intellij client. The connection test succeeds as well.

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

SQL Syntax Error Creating Table

I am getting the following error when I try to create a table in an SQL database:
Failed to create table 'references'
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in
your SQL syntax; check the manual that corresponds to your MySQL server version for
the right syntax to use near 'references(referenceID BIGINT NOT NULL AUTO_INCREMENT,
referenceText VARCHAR(255)'
Here is the code making the table:
public void createReferencesTable() {
System.out.println("Creating table '" + REFERENCE_TABLE + "'...");
Statement stmt = null;
try {
stmt = connection.createStatement();
stmt.executeUpdate("CREATE TABLE " + REFERENCE_TABLE + "("
+ REFERENCE_ID + " BIGINT NOT NULL AUTO_INCREMENT,"
+ REFERENCE_TEXT + " VARCHAR(255),"
+ REFERENCE_TWEET + " BIGINT NOT NULL,"
+ "PRIMARY KEY (" + REFERENCE_ID + ")"
+ ")");
System.out.println("Table '" + REFERENCE_TABLE + "' created");
} catch (SQLException e) {
System.err.println("Failed to create table '" + REFERENCE_TABLE + "'");
e.printStackTrace();
} finally {
if (stmt != null) {
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
And here are the declarations of the variables used:
public static final String REFERENCE_TABLE = "references";
public static final String REFERENCE_ID = "referenceID";
public static final String REFERENCE_TEXT = "referenceText";
public static final String REFERENCE_TWEET = "referenceTweet";
Also, I am creating two tables before this one that successfully work with basically the exact same syntax as this one, which is failing. Also, the MySQL server I am putting this databases into is fresh and just set-up, so there shouldn't be any configuration issues, as my program is connecting to the database successfully.
My question is: Why is this giving an error?
Notes: I have tried to do the reference ID line with an identity, but that did not make any difference. As I said before, the two functions each creating a table before this used exactly the same syntax, but gave no errors and successfully created their tables.
references is a reserved word in MySQL. Either use backticks to escape it or use another name.
stmt.executeUpdate("CREATE TABLE `" + REFERENCE_TABLE + "` ("
^-----------------------^-----------here

Cannot insert data into a table in db using jdbc

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.

Categories