I'm not sure why my program isn't creating the table but I also need some ideas on how to fill the table with code like this once it's created? I need to add two more tables to this database too.
This is the error I'm getting :
java.sql.SQLSyntaxErrorException: Table/View 'PIZZASIZE' does not exist.
Caused by: ERROR 42X05: Table/View 'PIZZASIZE' does not exist.
Caused by: java.lang.RuntimeException: Exception in Application start method
Caused by: javafx.fxml.LoadException: file:/C:/Users/Allie/Documents/NetBeansProjects/Pizzeria_AllieBeckman/dist/run1674141987/Pizzeria_AllieBeckman.jar!/pizzeria_alliebeckman/FXMLDocument.fxml
This is the code that's supposed to create the table:
// connect to the derby URL using the given username and password
connect = DriverManager.getConnection("jdbc:derby://localhost:1527/pizzeria;create=true", connectProps);
// current url for pre created database "jdbc:derby://localhost:1527/pizza"
// if connection is successful print that it succeeded.
System.out.println("database created");
stmt = connect.createStatement();
String sqlCreate = "CREATE TABLE PIZZASIZE "
+ "(id int NOT NULL, "
+ "size char(20) NOT NULL, "
+ "PRIMARY KEY (id))";
stmt.execute(sqlCreate);
Depending on the IDE you are using you could manually create the table in a console without going through the trouble of writing it in code. Here are some examples of how you could get the information from the tables.
Connection conn = CreatingDerbyDJB.dbConnection();
try{
String query = "INSERT INTO Items (Name,Color,ItemName,SchoolName, Description) VALUES(?,?,?,?, ?)";
PreparedStatement pstmt = conn.prepareStatement(query);
pstmt.execute();
conn.close();
}catch(Exception e)
{
e.printStackTrace();
} }
Here is what the Connection class should look like:
package main;
import java.sql.Connection;
import java.sql.DriverManager;
import javax.swing.JOptionPane;
public class CreatingDerbyDJB
{
public static final String DRIVER = "org.apache.derby.jdbc.EmbeddedDriver";
public static final String JDBC_URL = "jdbc:derby:LostAndFoundDB";
public static Connection dbConnection()
{
try
{
Class.forName(DRIVER).newInstance();
Connection c = DriverManager.getConnection(JDBC_URL);
return c;
}catch(Exception e)
{
JOptionPane.showMessageDialog(null, e);
return null;
}
}
}
Approve this answer if this helped you, I'd be happy to explain things if it does not make sense. :)
Related
The database update method that I'm working on in my java program, doesn't update the database. Only if I run the read method inside the same class, it will show the updated version of the database but it doesn't actually update the database.
What I do is I run the unit_elimination(2) method inside my main class and then it doesn't update the database ( it should turn the status column of the row with ID=1 inside main_table to 2 but it stays the same in the database ) . Then I use the showname method to read the table and it shows the updated number but the database isn't actually getting updated.
package com.company;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
import java.sql.PreparedStatement;
import java.sql.*;
public class Stdn implements AutoCloseable{
private Connection connection;
private PreparedStatement preparedStatement;
private ResultSet resultSet;
public Stdn() throws SQLException {
connection = DriverManager
.getConnection("jdbc:mysql://localhost:1522/juni_project" , "root", "password");
connection.setAutoCommit(false);
}
public void showName(String A , String B) throws SQLException{
preparedStatement = connection.prepareStatement("select "+ A + " from " + B + ";" );
resultSet = preparedStatement.executeQuery();
while (resultSet.next()){
System.out.println(resultSet.getString(1));
}
}
public void update(String A , String B , int C , int D) {
try{
PreparedStatement preparedStatement = connection.prepareStatement("UPDATE "+ A + " SET " + B + " =? WHERE ID = ? ;");
preparedStatement.setInt(1,C);
preparedStatement.setInt(2, D);
preparedStatement.executeUpdate();
}
catch (SQLException e){
System.out.println( " Could not update data to the database " + e.getMessage());
}}
public void unit_elimination(int X) throws SQLException {
update("main_table" ,"status", X , 1 );
}
#Override
public void close() throws Exception {
preparedStatement.close();
connection.close();
}}
Can you please help me find where the problem is I've been stuck on this for a few days and have little time to spare.
You disable auto-commit after creating the connection. This means you have to explicitly commit (using connection.commit()) before changes are visible to other transactions. And, IIRC, MySQL or MySQL Connector/J will rollback the transaction if it is still active when you close the connection.
In other words, your changes are 1) never visible to other transactions and 2) once you close the connections, your changes are gone.
TL;DR: Add a connection.commit() where your unit-of-work is complete and you want the changes to become permanent. Or consider if for your program using auto-commit is good enough, and remove the connection.setAutoCommit(false); from your code.
I have created a simple database application with Java and MySQL. I would like for the use to specify what they want to call the database and then have it created. I get an SQL syntax error when I run the following code:
private void jButton5ActionPerformed(java.awt.event.ActionEvent evt) {
try{
Class.forName("com.mysql.jdbc.Driver");
connect.con = DriverManager.getConnection("jdbc:mysql://localhost/?user=root&password=pass");
connect.st = connect.con.createStatement();
String dbName = jTextField19.getText().trim();
System.out.println(dbName);
String sql = "CREATE DATABASE'"+dbName+"'";
int rs = connect.st.executeUpdate(sql);
System.out.println("Database Created");
}catch(Exception e){
}
}
What am I doing wrong? An explanation is much appreciated.
"CREATE DATABASE'"+dbName+"'";
should be (note the additional space):
"CREATE DATABASE "+dbName;
I am trying to insert data into Derby embedded database for my Desktop Application. But Derby is giving me error of Schema Not found error.
I have tried to solve error by creating schema as per username, but does not solve my problem. I searched internet, but none of given solution solved my problem.
package derbyd.ui;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class AddStudent extends javax.swing.JFrame {
private void bt_saveActionPerformed(java.awt.event.ActionEvent evt) {
String conURL = "jdbc:derby:myDB;create=true";
String user = "SOURABH";
String passwd = "pass";
Connection con = null;
Statement st = null;
String query;
ResultSet rs = null;
try
{
Class.forName("org.apache.derby.jdbc.EmbeddedDriver");
con = DriverManager.getConnection(conURL, user, passwd);
st = con.createStatement();
System.out.println("Connection established");
query = "INSERT INTO SOURABH.MyTable VALUES('"+txt_name.getText()+"','"+txt_surname.getText()+"')";
st.executeUpdate(query);
System.out.println("Added Successfully");
}
catch(Exception e)
{
System.out.println("Error ->"+e);
}
}
}
According to the Frequently Asked Questions of Apache Derby, you will see that:
A schema is only created by CREATE SCHEMA or creating an object (table etc.) in that schema (this is implicit schema creation).
In your code, you need create the table first and then work like a charm.
Class.forName("org.apache.derby.jdbc.EmbeddedDriver");
con = DriverManager.getConnection(conURL, user, passwd);
st = con.createStatement();
System.out.println("Connection established");
st.executeUpdate("CREATE TABLE MyTable" +
"(name VARCHAR(255), surname varchar(255))");
System.out.println("Table created");
query = "INSERT INTO SOURABH.MyTable VALUES(" +
"'" + txt_name.getText() + "','" + txt_surname.getText() + "')";
st.executeUpdate(query);
System.out.println("Added Successfully");
The output is:
Connection established
Table created
Added Successfully
If you run this statement more than once, you'll get an error because the table already exists. To deal with that, here.
the easiest solution is to configure your database properties and make schema the same as user name but in capital litters
ex:
schema APP
user app
hope my answer can help.
I'm trying to connect Java and MySQL with JDBC connector. So, I've downloaded connector from official cite, added it to classpath and added to the libraries of eclipse.
Now i'm using the code below
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class LocalhostDBConnection
{
LocalhostDBConnection()
{
Connection connection;
try {
// Название драйвера
String driverName = "com.mysql.jdbc.Driver";
Class.forName(driverName);
// Create a connection to the database
String serverName = "localhost";
String mydatabase = "AvtoKovriki";
String url = "jdbc:mysql://" + serverName + "/" + mydatabase;
String username = "root";
String password = "";
connection = DriverManager.getConnection(url, username, password);
System.out.println("is connect to DB" + connection);
String query = "Select * FROM users";
Statement stmt = connection.createStatement();
ResultSet rs = stmt.execute(query);
String dbtime;
while (rs.next())
{
dbtime = rs.getString(1);
System.out.println(dbtime);
} // end while
connection.close();
} // end try
catch (ClassNotFoundException e)
{
e.printStackTrace();
// Could not find the database driver
} catch (SQLException e)
{
e.printStackTrace();
// Could not connect to the database
}
}
}
But in string: ResultSet rs = stmt.execute(query); there is a mistake "Type mismatch: cannot convert from boolean to ResultSet".
I can't understand what the problem is. Need some help.
The Statement#execute method returns a boolean. You are looking for the Statement#executeQuery method, which returns a ResultSet.
Your code should be like this:
ResultSet rs = stmt.executeQuery(query);
Firstly, this has nothing to do with MySQL - you're not getting as far as running the code, and none of your code deals with MySQL-specific types. (My point is that you may or may not have the MySQL jar file in the right place; this error isn't due to that.)
If you look at the documentation for Statement.execute(String) you'll see that that returns boolean, not ResultSet. That's why you're getting the compile-time error.
You want executeQuery(String) instead - or you could call execute(String), and if it returns true, call getResultSet.
You need to use executeQuery(String sql) method
see javadocs for more details about the provided methods
http://docs.oracle.com/javase/6/docs/api/java/sql/Statement.html
stmt.execute(query);
returns boolean not ResultSet. You can get
ResultSet by using stmt.executeQuery() method for queries that won't
modify data in the database.
If you want to modify data in your Database use the executeUpdate() method, which will return an integer to indicate whether data has been modified or not.
I have a postgres database and a table named "state_master". I'm simply fetching the data from this table by the following code.
import java.sql.*;
public class Test1
{
public static void main(String... s1)
{
try{
Class.forName("org.postgresql.Driver");
Connection con = DriverManager.getConnection("jdbc:postgresql://localhost:5432:secc_db","postgres", password");
Statement s = con.createStatement();
ResultSet rs = s.executeQuery("Select * from state_master");
}catch(SQLException e){ System.out.println(e);}
catch(Exception i){System.out.println(i);}
}
}
All I get is an error: relation state_master does not exist. Please help me to sort out this problem.
The erroe means the table state_master is not exist in the user(Database) postgres. Check whether you have created the table state_master in your database or not. If not first create the table then try to execute the program.
Your connect url is not correct. you are using colon(:) for specifying the database.
It should be a slash(/) like : "jdbc:postgresql://localhost:5432/secc_db"