When I run my program, there is a Null Pointer Exception associated with createCarMaker. I checked the DB connection and it seems all okay. May I please have some help troubleshooting.
CarDBHelper(){
try
{
//Establish a driver
Class.forName("com.mysql.jdbc.Driver").newInstance();
//Connect to the database
conn = DriverManager.getConnection(URL, USERNAME, PASSWORD);
}
catch (Exception e)
{
System.err.println("Unable to load MySQL driver.");
e.printStackTrace();
}
}
/**
* Creates the tables carMaker and Vehicle with various parameters.
*
*/
public void createTables(){
try {
Statement stmt=conn.createStatement();
String createcarMaker = "CREATE TABLE carMaker " +
"(makerID INT AUTO_INCREMENT NOT NULL, " +
" makerName VARCHAR(50), " +
" PRIMARY KEY ( makerID ))";
statement.executeUpdate(createcarMaker);
String createVehicle = "CREATE TABLE Vehicle " +
"(id INT AUTO_INCREMENT NOT NULL, " +
" year INT, " +
" make INT, " +
" model VARCHAR(50), " +
" FOREIGN KEY (make) REFERENCES carMaker(makerID)," +
" PRIMARY KEY ( id ))";
statement.executeUpdate(createVehicle);
} catch (SQLException e) {
e.printStackTrace();
}
I think you are using wrong declared variable of Statement in 'statement' and 'stmt'.
Furthermore please put the stack trace here.
You are using an undeclared variable. You declare:
Statement stmt=conn.createStatement();
But then reference:
statement.executeUpdate(createcarMaker);
stmt != statement.
Related
I have code in eclipse that creates tables for mysql database, but after the initial creation it throws the error 'table already exists'. Is there a way to ignore this error so that it doesn't appear in the console when executing the code? I'm not sure if to do so I have to do something to my code or if its something to be changed in Eclipse, but in case I included my code below if need be
package project_files;
import java.sql.*;
import javax.swing.JOptionPane;
public class database {
// JDBC driver name and database URL
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost/userdatabase";
// Database credentials
static final String USER = "root";
static final String PASS = "pass1234";
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
try{
//STEP 3: Open a connection
System.out.println("Connecting to a selected database...");
conn = DriverManager.getConnection(DB_URL, USER, PASS);
System.out.println("Connected database successfully...");
//STEP 4: Execute a query
System.out.println("Creating table in given database...");
stmt = conn.createStatement();
String sql = "CREATE TABLE review " +
"(video_name VARCHAR(45) not NULL, " +
" review_comments VARCHAR(45), " +
" review_star VARCHAR(45), " +
" PRIMARY KEY ( video_name ))";
String sql1= "CREATE TABLE user " +
"(FirstName VARCHAR(45) not NULL, " +
" LastName VARCHAR(45), " +
" City VARCHAR(45), " +
" DOB VARCHAR(45), " +
" Phone Number BIGINT(20), " +
" Email VARCHAR(45), " +
" PRIMARY KEY ( Email ))";
String sql2= "CREATE TABLE video " +
"(video_name VARCHAR(45) not NULL, " +
" video_description VARCHAR(45), " +
" video_city VARCHAR(45), " +
" video_tags VARCHAR(45), " +
" video_subject VARCHAR(45), " +
" PRIMARY KEY ( video_name ))";
stmt.executeUpdate(sql);
stmt.executeUpdate(sql1);
stmt.executeUpdate(sql2);
System.out.println("Created table in given database...");
}catch(SQLException se){
//Handle errors for JDBC
se.printStackTrace();
}catch(Exception e){
//Handle errors for Class.forName
e.printStackTrace();
}finally{
//finally block used to close resources
try{
if(stmt!=null)
conn.close();
}catch(SQLException se){
}// do nothing
try{
if(conn!=null)
conn.close();
}catch(SQLException se){
se.printStackTrace();
}//end finally try
}//end try
JOptionPane.showMessageDialog(null, "Tables created successfully");
}//end main
}//end JDBCExample
You could use IF NOT EXISTS:
Prevents an error from occurring if the table exists. However, there is no verification that the existing table has a structure identical to that indicated by the CREATE TABLE statement.
CREATE TABLE IF NOT EXISTS review(...);
This has been driving me crazy and I'm sure it's something simple. I'm getting a 'values must contain at least one element' error from server when I try to input a reservation from the table that comes up. It's all running ok. No matter if I use quotes in the VALUES section or plus(+)symbols or quotes over the separating commas I get different error messages. When I put quotes over table_num I get and error telling me that you cant insert CHAR into INTEGER. When I remove quotes I get error telling me -
Severe: java.sql.SQLSyntaxErrorException: Column 'TABLE_NUM' is either not in any table in the FROM list or appears within a join specification etc. Could anyone tell me what is going on? Here's the jsp code. Thanks in advance.
<%
int tableNum = 0;
String firstName = null;
String lastName = null;
String Address = null;
int Phone = 0;
java.sql.Date date = null;
int People = 0;
if (request.getParameter("table_num")!=null){
tableNum = Integer.parseInt(request.getParameter("table_num"));
}
if (request.getParameter("first")!=null){
firstName = request.getParameter("first");
}
if (request.getParameter("last")!=null){
lastName = request.getParameter("last");
}
if (request.getParameter("address")!=null){
Address = request.getParameter("address");
}
if (request.getParameter("phone")!=null){
Phone = Integer.parseInt(request.getParameter("phone"));
}
if (request.getParameter("date")!=null){
java.util.Date utilDate = new java.util.Date(request.getParameter("date"));
date = new java.sql.Date(utilDate.getTime());
}
if (request.getParameter("people")!=null){
People = Integer.parseInt(request.getParameter("people"));
}
if(tableNum != 0 && firstName != null && lastName != null && Address != null && Phone != 0 && date != null && People != 0){
String URL = "jdbc:derby://localhost:1527/Reservations";
String USERNAME= "johnpaul";
String PASSWORD= "purlease";
Connection myCon = null;
Statement ste = null;
PreparedStatement preparedStmt = null;
try{
Class.forName("org.apache.derby.jdbc.ClientDriver");
System.out.println("Connecting to DB...");
Connection con=DriverManager.getConnection("jdbc:derby://localhost:1527/Reservations","johnpaul", "purlease");
System.out.println("Connected successfuly");
System.out.println("Inserting records into table");
Statement st = con.createStatement();
String query = "INSERT INTO JOHNPAUL.CUSTOMER_RESERVATIONS(TABLE_NUM,FIRST_NAME,LAST_NAME,ADDRESS,TELEPHONE,DATE,NUMBER_IN_PARTY)VALUES(table_num,first,last,address,phone,date,people)";
st.executeUpdate (query);
System.out.println("Records inserted");
}catch(SQLException se){
se.printStackTrace();
}catch(ClassNotFoundException se){
//Handle errors for JDBC
se.printStackTrace();
}catch(Exception e){
//Handle errors for Class.forName
e.printStackTrace();
}
}
%>
Your problem appears to be here:
String query = "INSERT INTO JOHNPAUL.CUSTOMER_RESERVATIONS
(TABLE_NUM, FIRST_NAME,LAST_NAME,ADDRESS,TELEPHONE, DATE, NUMBER_IN_PARTY)
VALUES (table_num, first,last,address,phone,date,people)";
Two things here:
1. Escape your strings; and
2. Concatenate the values in your variables to the string.
String query = "INSERT INTO JOHNPAUL.CUSTOMER_RESERVATIONS
(TABLE_NUM, FIRST_NAME,LAST_NAME,ADDRESS,TELEPHONE, DATE, NUMBER_IN_PARTY)
VALUES (" + table_num + ", '" + first + "', '" + last + "', '" + address + "', " + phone + " , '" + date + "', " + people + ");";
You may have to verify the format that your database engine expects the date field.
I am writing a simple database with a query that inserts some data, modifies a entry, deletes it, then prints out the rest.
import java.sql.*;
public class SpotifyDB {
//JDBC driver name and database URL
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost/spotify";
static final int portNumber = 3306;
static final String serverName = "localhost";
static final String dbName = "spotify";
//Database credentials
static final String USER = "root";
static final String PASS = "root";
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
try{
//Register JDBC driver
Class.forName("com.mysql.jdbc.Driver");
//Open a connection to the database
System.out.println("Connecting to a selected database...");
conn = DriverManager.getConnection(DB_URL, USER, PASS);
System.out.println("Connected database successfully...");
//Insert data
System.out.println("Inserting records into the table...");
stmt = conn.createStatement();
String sql = "INSERT INTO artist(artist) " +
"values('Muse')";
stmt.executeUpdate(sql);
sql = "INSERT INTO album(album, artist, genre, year)" +
"values('Drones', 'Muse', 'Rock', 2015)";
stmt.executeUpdate(sql);
sql = "INSERT INTO album(album, artist, genre, year)" +
"values('The 2nd Law', 'Muse', 'Rock', 2012)";
stmt.executeUpdate(sql);
sql = ("INSERT INTO songs(song, artist, album, tracknumber, duration)" +
"values('Madness', 'Muse', 'The 2nd Law', 2, '4:41')");
stmt.executeUpdate(sql);
sql = ("INSERT INTO songs(song, artist, album, tracknumber, duration)" +
"values('Mercy', 'Muse', 'Drones', 4, '3:52')");
stmt.executeUpdate(sql);
System.out.println("Records inserted into the table!");
//Update data
String sql1 = "UPDATE songs " +
"SET track number = 1 WHERE song in ('Madness')";
stmt.executeUpdate(sql1);
//Delete data
String sql2 = "DELETE FROM songs " +
"WHERE song = Madness";
stmt.executeUpdate(sql2);
//View records
String sql3 = "SELECT * FROM songs";
ResultSet rs = stmt.executeQuery(sql3);
while(rs.next()) {
//Retrieve by column name
String song = rs.getString("song");
String artist = rs.getString("artist");
String album = rs.getString("album");
String track = rs.getString("track number");
String duration = rs.getString("duration");
//Display the values
System.out.print("Song: " + song);
System.out.print(", Artist: " + artist);
System.out.print(", Album: " + album);
System.out.println(", Track: " + track);
System.out.println(", Duration: " + duration);
}
//Close the connection, clean up running functions
rs.close();
stmt.close();
conn.close();
}
catch(SQLException se) {
//Handle errors for JDBC driver
se.printStackTrace();
}
catch(Exception e) {
//Handle errors for Class.forName
e.printStackTrace();
}
finally {
//finally used to close resources
try{
if(stmt!=null)
stmt.close();
}
catch(SQLException se2) {
}
try{
if(conn!=null)
conn.close();
}
catch(SQLException se) {
se.printStackTrace();
}
}
System.out.println("Goodbye!");
}
}
My SQL Database table is quite simple as well;
CREATE TABLE spotify.`songs` (
`song` varchar(20) NOT NULL,
`artist` varchar(20) NOT NULL,
`album` varchar(20) NOT NULL,
`track number` int(3) NOT NULL,
`duration` varchar(10) NOT NULL,
PRIMARY KEY (`song`),
KEY `songalbum_idx` (`album`),
KEY `songartist` (`artist`),
CONSTRAINT `songalbum` FOREIGN KEY (`album`) REFERENCES `album` (`album`)
ON DELETE CASCADE
ON UPDATE CASCADE,
CONSTRAINT `songartist` FOREIGN KEY (`artist`) REFERENCES `artist` (`artist`)
ON DELETE CASCADE
ON UPDATE CASCADE);
and the console is returning me this error: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException
I am having trouble seeing where the table columns are not matching up, any help would be appreciated. Thank you!
Column names really shouldn't have spaces, for exactly this reason. But if your column names must have spaces then you need to qualify them with back-ticks exactly as you do in your CREATE TABLE statement:
INSERT INTO songs (song, artist, album, `track number`, duration) VALUES ...
Otherwise after the identifier track the query engine is expecting either a comma (to move on to another identifier) or a close parentheses (to end the list of column identifiers). It finds neither of this, and immediately finds another identifier (number, which may even be a reserved word?). This confuses the query parser.
I have been working on a database for sometime now and i got stocked a particular section. I am trying to write a code to control the foreign key column in a database. mysql is the back-end and Java is the front-end.
Already worked on the faculty table with this code :
try {
String DATABASE_URL = "jdbc:mysql://localhost/accomodation";
String username = "root";
String password = "";
Connection con = DriverManager.getConnection(DATABASE_URL,username,password);
Statement stmt = con.createStatement();
String Query = "INSERT INTO faculty( Name, DeanName, Email) values ('"
+ facCombo.getSelectedItem() + "', '"
+ deanTF.getText() + "', '"
+ facmailTF.getText() + "')";
stmt.executeUpdate(Query);
JOptionPane.showMessageDialog(this, "Inserted Successfully", "Status",
JOptionPane.INFORMATION_MESSAGE);
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "incorrect");
}
The database is linked as faculty to department and the department has the foreign key referencing the faculty table but have tried writing a query referencing it all to no avail.
Will be grateful if someone can help me out.
I would like to insert data into my sqlite data base but with a variable as the name of the table where the data should be entered.
try {
Random rand = new Random();
uniqueID = rand.nextInt(9998) + 1; //Generates a random number from 1 - 9999 inclusively
String dateStart = day1.getText() + "/" + month1.getText() + "/" + year1.getText();
String dateEnd = day2.getText() + "/" + month2.getText() + "/" + year2.getText();
String projectN = projectName.getText();
String addr = address.getText();
//String engineerN = engineerName.getText();
//String engineerP = engineerPassword.getText();
Class.forName("org.sqlite.JDBC");
conn2.setAutoCommit(false);
PreparedStatement ps = conn2.prepareStatement("insert into "My table name" (uniqueid,name,address,startingdate,estcompletion) values(?,?,?,?,?,?)");
ps.setInt(1, uniqueID);
ps.setString(2, projectN);
ps.setString(3, addr);
ps.setString(4, dateStart);
ps.setString(5, dateEnd);
//ps.setString(6, engineerN);
ps.execute();
ps.close();
conn2.commit();
conn2.close();
}
catch ( Exception e1) {
System.err.println( e1.getClass().getName() + ": " + e1.getMessage() );
System.exit(0);
}
}
}
public String JJI() {
return projectName.getText();
}
}
"My table name" in the prepared statement is the place where I want to put my table name getting it from projectName.getText(); at the end. The user enters projectname.getText in another class.
Thank you for the help!
Store your table name in a String variable (how you like): String tableName = "users";
Make a query variable that contains your SQL query:
String query = "insert into '" + tableName + "' (uniqueid,name,address,startingdate,estcompletion) values(?,?,?,?,?,?)";
If you would like to have variables to insert, replace the "?" with your variable names as you have done in your code:
ps.setInt(1, uniqueID);
ps.setString(2, projectN);
ps.setString(3, addr);
ps.setString(4, dateStart);
ps.setString(5, dateEnd);
Execute the query:
PreparedStatement ps = conn2.prepareStatement(query);
ps.execute();