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;
Related
ConnectionClass:
Here I used stm.execute but I'm not getting an error. I also used executeUpdate but I'm also getting an error.
package com.company;
import java.sql.*;
class ConnectionClass {
private static Connection con = null;
private static Statement stm = null;
private static ConnectionClass connectionClass;
public void createConnection() {
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/mysql", "root", "root");
}
catch (Exception e) {
e.printStackTrace();
}
}
public void createTable() {
String Table_Name = "BOOK";
try {
stm = con.createStatement();
DatabaseMetaData dbm = con.getMetaData();
ResultSet rs = dbm.getTables(null, null, Table_Name, null);
if (rs.next()) {
System.out.println("Table" + Table_Name + "Already created");
} else {
String sql = "CREATE TABLE" + Table_Name + "(ID VARCHAR(200), title VARCHAR(200),author varchar(100),publisher varchar(100)";
stm.executeLargeUpdate(sql);
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
public ConnectionClass() {
createConnection();
createTable();
}
}
MainClass:
Here I think the main class is working properly.
package com.company;
public class Main {
public static void main(String[] args) throws Exception {
ConnectionClass connectionClass = new ConnectionClass();
}
}
ERROR:
The method executeLargeUpdate was added in Java 8 / JDBC 4.2 and judging by the error it has not been implemented in the MySQL Connector/J version you are using.
The solution is simple: don't use any of the Large methods in the API, and instead use executeUpdate, or - better in the case of DML - execute. Alternatively, update to a newer version of MySQL Connector/J, as executeLargeUpdate is implemented in newer versions of MySQL Connector/J (eg 5.1.46, but at least 5.1.37 (the version that added support)).
You will also need to address the syntax error pointed out by Adil.
You have a syntax error in your query. You current SQL Query:
String sql = "CREATE TABLE" + Table_Name + "(ID VARCHAR(200), title VARCHAR(200),author varchar(100),publisher(100)";
Corrected SQL Query:
String sql = "CREATE TABLE" + Table_Name + "(ID VARCHAR(200), title VARCHAR(200),author varchar(100),publisher varchar(100)";
(You are asking mysql to create a column publisher, but where's the datatype? Simply specify the datatype and it will work.)
EDIT:
So, finally wrapping up this question, let's have a look at what Ora Docs have to say about this:
executeLargeUpdate:
default long executeLargeUpdate(String sql) throws SQLException
Executes the given SQL statement, which may be an INSERT, UPDATE, or DELETE statement or an SQL statement that returns nothing, such as an SQL DDL statement.
This method should be used when the returned row count may exceed Integer.MAX_VALUE - A constant holding the maximum value an int can have, 2^31-1.
Note:This method cannot be called on a PreparedStatement or CallableStatement.
The default implementation will throw UnsupportedOperationException. This method is introduced since JDK 1.8
Also note the above point as stated in the docs. The default implementation is to throw an UnsupportedOperationException. This means that different JDBC drivers can have different implementations of Statement class. They can either implement it or leave it unimplemented, and if you invoke the method in 2nd case, the method will throw an UnsupportedOperationException, as stated in the docs.
By checking the oracle docs for this method, you can get more information about it. So the possibility could be that the driver version you are using is not supporting this method, so please update tot eh latest version of this driver and try it out.
I'm looking for a way to get information about triggers (like name and other details) in MS_SQL, MySQL, PostgreSQL, and Oracle.
I found the following code in this answer but when I tried using it with a MySQL database it did not work.
package jdbc.core;
import java.sql.*;
public class ListProcedures {
public static void main(String[] args) {
Connection con = null;
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/db1", "root", "xxx");
DatabaseMetaData meta = con.getMetaData();
ResultSet res = meta.getTables(null, "root", "public", new String[] { "TRIGGER" });
System.out.println("List Of the trigger :-");
while (res.next()) {
// res.getString("TABLE_NAME");
System.out.println("!!" + res.getString(1));
System.out.println("::" + res.getString(2));
System.out.println("::" + res.getString(3));
}
res.close();enter code here
con.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Can anyone suggest some other way to retrieve the information I need?
There is nothing in JDBC that defines how to obtain information on triggers. This means you can only use driver-specific quirks like using a 'table'-type "TRIGGER" with Oracle, or maybe a driver-specific extension in another driver.
So in general the answer is: you can't.
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. :)
I am following a tutorial on connecting my SQLite database to a Java application.
When I run the program I get the following error in the console of NetBeans:
run:
Error connecting to the databasejava.sql.SQLException: No suitable
driver found for jdbc:C:\Users\lawman\Documents\Java Working
Directory\LoginSql\src\project123.sqlite
BUILD SUCCESSFUL (total time: 0 seconds)
Here is my directory:
I have code to connect to the database in class tobecalledbymain.
I have main in mainclass which creates an instance of tobecalledbymain.
In my library file, I have sqlite-jdbcs.jar imported.
Here is the code for tobecalledinmain:
import java.sql.*;
public class tobecalledinmain {
public tobecalledinmain(){
Connection con = null;
Statement st=null;
ResultSet rs=null;
try
{
Class.forName("org.sqlite.JDBC");
con = DriverManager.getConnection("jdbc:C:\\Users\\lawman\\Documents\\"
+ "Java Working Directory\\LoginSql\\"
+ "src\\project123.sqlite");
st=con.createStatement();
//select all records from the table employee
//table has three firlds: employeeid,name and surname
rs=st.executeQuery("SELECT * FROM Employee;");
while (rs.next())
{
int id = rs.getInt("Employeeid");
String name = rs.getString("Name");
System.out.println("id = " + id);
System.out.println("name= " + name);
System.out.println();
}
rs.close();
st.close();
con.close();
}catch(Exception e)
{
System.out.println("Error connecting to the database" + e);
}
}
}
Here is the mainclass code:
public class mainClass {
public static void main(String[] args){
new tobecalledinmain();
}
}
;;
I am not sure why we need to semi-colons!
Anyway, when the tutorial concludes he gets a result from the console. I get the said error message.
What are the drivers in the error message referring to and how do I get them?
Your jdbc connection string does not specify sqlite. Try this, and use forward slashes.
Connection con = DriverManager.getConnection("jdbc:sqlite:C:/PATH/TO/database.db");
This was the WRONG answer, pls disregard.
You need to add the .jar for the SQLite database driver to your classpath when you run your code. See https://bitbucket.org/xerial/sqlite-jdbc
You can see how to do that in Netbeans here: How to add a JAR in NetBeans
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"