I am trying to connect my java project to the database.
I am creating a method to create a table using this code
package DataBaseConnectivity;
import java.sql.Connection;
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.Statement;
import java.util.Scanner;
public class DataBaseConnectivity {
public static void main(String args[]) {
// Creating the connection using Oracle DB
// Note: url syntax is standard, so do grasp
String url = "jdbc:sqlserver://localhost:1433;databaseName=SchoolMgt;encrypt=true;trustServerCertificate=true";
// Username and password to access DB
// Custom initialization
String user = "sa";
String pass = "root";
// Entering the data
Scanner scanner = new Scanner(System.in);
String tableCreationsql = " create table Students ( id integer PRIMARY KEY,fname VARCHAR (8),birthdate date,lname VARCHAR (8))";
Connection con = null;
// Try block to check for exceptions
try {
Driver driver = (Driver) Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver").newInstance();
// Registering drivers
DriverManager.registerDriver(driver);
// Reference to connection interface
con = DriverManager.getConnection(url, user, pass);
// Creating a statement
Statement st = con.createStatement();
// Executing query
int Executing = st.executeUpdate(tableCreationsql);
if (Executing >= 1) {
System.out.println("Created Successfully : " + tableCreationsql);
} else {
System.out.println("Creation Is Failed");
}
// Closing the connections
con.close();
}
// Catch block to handle exceptions
catch (Exception ex) {
// Display message when exceptions occurs
System.err.println(ex);
}
}
}
The code works fine but it never enters the if condition
it directly move to the else
Also the table is some how is created even though it goes to else
I am expecting to get Creation is successful and table shall be created in database.
executeUpdate returns the number of rows affected (see the documentation)
Since you are creating a table (DDL statement) 0 rows are affected, hence Executing equals 0
Related
Trying to first make sure this part of my project is working before implementing it into a GUI.
Trying to first create a new table in the data base called n012345_Accounts with 4 columns:
Account Number
Name
Balance
Lock
Then I want to populate the data of this table by reading the lines of the file I have created with in Accounts.txt which includes the following
Number Name Balance Locked
1001 Isabel_Newton 2000 yes
1002 Blake_Wool 1500 yes
1003 Martha_Curie 3000 no
1004 Nortom_Eef 1500 no
1009 Dan_Heckler 2000 yes
1010 Timothy_Wicket 4000 no
1011 Jane_Doe 5000 no
The purpose of this is to practice my understanding of using PreparedStatements and transactions. If anyone can see what the error is that is not allowing the creation of the table I would appreciate the input.
Currently when running my project the console returns
unable to create new table for accounts
//Create a GUI application for a bank
//it should manage fund transfers from one account to another
//1
//Start
//# the start up it should create a table name YourStudentNumber_Accounts ( n012345)
//it should also populate this table with the information stored in the file provided ("Accounts.txt")
//2
//Then the application will ask for
//account number the funds are to be transferred from
//amount to be transferred
//account number funds are to be transferred to
//3
//Upon exit the application will present the contents of the Accounts table in standard output
//USE PREPARED STATEMENTS and TRANSACTIONS wherever appropriate
//All exceptions must be handled
import oracle.jdbc.pool.OracleDataSource;
import java.io.*;
import java.sql.*;
public class Main {
public static void main(String[] args) throws SQLException{
OracleDataSource ods = new OracleDataSource();
ods.setURL("jdbc:oracle:thin:n012345/luckyone#calvin.humber.ca:1521:grok");
//try to connect to the database connection we have declared
try(Connection con = ods.getConnection()) {
//create a statement object
try (Statement stmt = con.createStatement()) {
try (ResultSet rs = stmt.executeQuery("CREATE TABLE n012345_Accounts (AccountNumber float(4) , Name varchar(25), Balance float(9), Lock varchar(25))")) {
try (BufferedReader reader = new BufferedReader(new FileReader("Accounts.txt"));) {
String line;
//do not automatically commit statements
con.setAutoCommit(false);
while ((line = reader.readLine()) != null) {
//inputting data into a String array splitting data by the space between the items in the file
String[] fields = line.split(" ");
String queryString = "INSERT INTO n012345_Accounts (AccountNumber, Name, Balance, Lock) VALUES(?,?,?,?)";
try (PreparedStatement statement = con.prepareStatement(queryString);) {
statement.setFloat(1, Float.parseFloat(fields[0]));
statement.setString(2, fields[1]);
statement.setFloat(3, Float.parseFloat(fields[2]));
statement.setString(4, fields[3]);
statement.executeUpdate();
} catch (Exception e) {
System.out.println("There was an error inserting into the database.");
}
System.out.println("Accounts.txt data was populated into the table n01494108_Accounts");
}
} catch (Exception e) {
System.out.println("unable to read the file.");
}
con.commit();
} catch (SQLException ex) {
System.out.println("unable to create new table for accounts");
}
//closes the statement
} catch (Exception e) {
//using rollback() to ensure no statements in a transaction are committed if an exception error occurs
con.rollback();
}
}catch (SQLException ex){
//closes connection
}
} //closes main method
} // closes main class
Use execute instead of executeQuery when you are trying to create a table.
Your code is printing unable to create new table for accounts because database table N012345_ACCOUNTS already exists. Once you create a database table, you can't re-create it. Hence the very first time you run your code – assuming that the database table does not exist – the database table will be successfully created however the next time you run your code, you will get unable to create new table for accounts – unless you drop the table before running your code again. By the way, I recommend printing the stack trace in catch blocks rather than just some error message alone.
You can use DatabaseMetaData to check whether the database table already exists and create it if it doesn't.
After creating the database table, your next task is to populate it. I recommend using batching.
You populate the database table with data that you read from a text file. You need to verify the data read from the text file. According to the sample text file contents in your question, you need to ignore the first two lines of the file.
The below code uses text blocks, NIO.2, try-with-resources and multi-catch.
import java.io.BufferedReader;
import java.io.IOException;
import java.math.BigDecimal;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class Main {
private static void createTable(Connection conn) throws SQLException {
String sql = """
create table N012345_ACCOUNTS (
ACCOUNT_NUMBER number(4)
,ACCOUNT_NAME varchar2(30)
,ACCOUNT_BALANCE number(14,2)
,ACCOUNT_LOCKED varchar2(3)
,constraint ACCT_PK primary key (ACCOUNT_NUMBER)
,constraint ACCT_LOCKS check (ACCOUNT_LOCKED in ('no','yes'))
)
""";
try (Statement s = conn.createStatement()) {
s.executeUpdate(sql);
System.out.println("Database table N012345_ACCOUNTS created.");
}
}
private static void populateTable(Connection conn) throws IOException, SQLException {
String sql = "insert into N012345_ACCOUNTS values (?, ?, ?, ?)";
Path path = Paths.get("accounts.txt");
try (BufferedReader br = Files.newBufferedReader(path);
PreparedStatement ps = conn.prepareStatement(sql)) {
String line = br.readLine();
conn.setAutoCommit(false);
while (line != null) {
String[] fields = line.split(" ");
if (fields.length == 4) {
try {
BigDecimal number = new BigDecimal(fields[0]);
String name = fields[1];
BigDecimal balance = new BigDecimal(fields[2]);
String locked = fields[3];
ps.setBigDecimal(1, number);
ps.setString(2, name);
ps.setBigDecimal(3, balance);
ps.setString(4, locked);
ps.addBatch();
}
catch (NumberFormatException xNumberFormat) {
// Ignore.
}
}
line = br.readLine();
}
int[] results = ps.executeBatch();
int success = 0;
for (int result : results) {
if (result == 1) {
success++;
}
}
System.out.printf("Inserted %d rows.%n", success);
if (success == results.length) {
conn.commit();
}
else {
conn.rollback();
}
}
}
public static void main(String[] args) {
String url = "jdbc:oracle:thin:n012345/luckyone#calvin.humber.ca:1521:grok";
try (Connection conn = DriverManager.getConnection(url)) {
DatabaseMetaData dbmd = conn.getMetaData();
ResultSet rs = dbmd.getTables(null, null, "N012345_ACCOUNTS", null);
if (!rs.next()) {
createTable(conn);
}
else {
System.out.println("Database table N012345_ACCOUNTS already exists.");
}
populateTable(conn);
}
catch (IOException | SQLException x) {
x.printStackTrace();
}
}
}
Refer to the following (in no particular order):
SQL Language Reference from Oracle database documentation.
JDBC Developer's Guide and Reference also from Oracle database documentation.
JDBC Database Access trail in Oracle's Java tutorials.
javadoc for method executeBatch in interface java.sql.Statement
Why is this code is not showing output after running it in Netbeans? It is supposed to ask "Enter username to search" after connecting to the database in mysql. I have created Database and Table in Netbeans 8.0.2 using MySql. All drivers are installed correctly as i can see them in service panel.I am using Netbeans 8.0.2 as i works on webservice. I am not sure if it is JDBC problem or something else, as I can access all Databases and Tables from Netbeans 8.0.2 perfectly. Please help.
public class Passwordchecker{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
try {
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/checksql", "username", "password");
Statement stmt = con.createStatement();
char answer;
do{
System.out.print("Enter username to search for: ");
String name = sc.next();
String SQL = "SELECT * FROM people WHERE name='" + name + "'";
ResultSet rs = stmt.executeQuery(SQL);
if(rs.next()) {
System.out.println("Success!");
} else {
System.out.println("Failure!");
}
System.out.print("Do you want to search for another name? (Y/N): ");
answer = sc.next().charAt(0);
} while(answer == 'Y' || answer == 'y');
} catch(Exception e) {
e.printStackTrace();
}
}
There are couple of things you can try to debug the code.
Here hard code a name.
String name = sc.next();
something like
String name = "An Existing name in DB";
your catch dont have any mechanism to print exception so you will never know what happened. Modify the catch:
catch(Exception e) {
e.printStackTrace();
}
Do this and let me know we will go from there.
Have you checked your code:
You need these imports
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Scanner;
In the code you have provided. You have missed "}" in end. Check it.
If you don't get any result is because the code execution is throwing an exception. When the execution reaches the exception part, there isn't more code to execute, so the program is finished and it doesn't show anything on the console.
I guess the statement stmt = con.createStatement(); part is throwing the exception try execute this code:
System.out.print("Posible Failure 1");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/checksql", "username", "password");
System.out.print("Posible Failure 2");
statement stmt = con.createStatement();
System.out.print("Posible Failure 3");
And add this line in the exception part:
catch(Exception e) {
e.printStackTrace();
}
This will tell you what and where exception is throwing.
Make sure the MYSQL service is running and you must have all the imports you need.
As per my requirement, I need to pull records from Teradata db. While trying to pull data, I am getting exception as follows.
com.teradata.jdbc.jdbc_4.util.JDBCException: [Teradata Database] [TeraJDBC 14.10.00.09] [Error 3932] [SQLState 25000] Only an ET or null statement is legal after a DDL Statement.
at com.teradata.jdbc.jdbc_4.util.ErrorFactory.makeDatabaseSQLException(ErrorFactory.java:307)
at com.teradata.jdbc.jdbc_4.statemachine.ReceiveInitSubState.action(ReceiveInitSubState.java:108)
at com.teradata.jdbc.jdbc_4.statemachine.StatementReceiveState.subStateMachine(StatementReceiveState.java:321)
at com.teradata.jdbc.jdbc_4.statemachine.StatementReceiveState.action(StatementReceiveState.java:202)
at com.teradata.jdbc.jdbc_4.statemachine.StatementController.runBody(StatementController.java:122)
at com.teradata.jdbc.jdbc_4.statemachine.StatementController.run(StatementController.java:113)
at com.teradata.jdbc.jdbc_4.TDStatement.executeStatement(TDStatement.java:380)
at com.teradata.jdbc.jdbc_4.TDStatement.executeStatement(TDStatement.java:322)
at com.teradata.jdbc.jdbc_4.TDStatement.doNonPrepExecuteQuery(TDStatement.java:310)
at com.teradata.jdbc.jdbc_4.TDStatement.executeQuery(TDStatement.java:1085)
at com.uprr.netcontrol.wkfl_mgmt.eventhandler.eventprocessor.TeradataSelectFromVolatileTable.main(TeradataSelectFromVolatileTable.java:26)
I think I got this exception because of using Volatile table in my query. But I need to use volatile table as part of query to make grouping on a particular column to get comma separated column data. Please, suggest me how to get result set while using volatile table in query. Here, I am enclosing sample java program to reproduce the exception.
package com.sample.package;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class TeradataSelectFromVolatileTable {
public static void main(String[] args) throws SQLException {
String url = "jdbc:teradata://<TERADATA_TABLE_NAME>";
final String query =
"CREATE VOLATILE TABLE VT_TEMP AS (" + "SELECT PERS_ID,FIR_NAME FROM <TABLE_NAME> AS PERSON)"
+ "WITH DATA UNIQUE PRIMARY INDEX(PERS_ID) ON COMMIT PRESERVE ROWS;" + // volatile table created.
"SELECT * FROM VT_TEMP;"; // pulling rows.
Connection con = null;
try {
System.out.println(" Looking for the Teradata JDBC driver... ");
// Loading the Teradata JDBC driver
Class.forName("com.teradata.jdbc.TeraDriver");
System.out.println(" JDBC driver loaded. \n");
con = DriverManager.getConnection(url, "<USER_ID>", "<PASSWORD>");
Statement stmt = con.createStatement();
System.out.println(" Statement object created. \n");
ResultSet rset = stmt.executeQuery(query);
//Some operations on resultset goes here...........
System.out.println(" total column count " + rset.getMetaData().getColumnCount());
} catch (Exception e) {
e.printStackTrace();
} finally {
// Close the statement
con.close();
System.out.println("\n Connection object closed. \n");
}
}
}
I think you may need to wrap your CT statement in an explicit, Teradata-mode transaction to resolve the error you are receiving:
public class TeradataSelectFromVolatileTable {
public static void main(String[] args) throws SQLException {
String url = "jdbc:teradata://<TERADATA_TABLE_NAME>";
final String query =
"BT;" + // Begin Teradata-mode Transaction
"CREATE VOLATILE TABLE VT_TEMP AS (" +
"SELECT PERS_ID,FIR_NAME FROM <TABLE_NAME> AS PERSON)"
+ "WITH DATA UNIQUE PRIMARY INDEX(PERS_ID) ON COMMIT PRESERVE ROWS;" + // volatile table created. +
"ET;" + // End Teradata-mode Transaction
"SELECT * FROM VT_TEMP;"; // pulling rows.
Connection con = null;
try {
System.out.println(" Looking for the Teradata JDBC driver... ");
// Loading the Teradata JDBC driver
Class.forName("com.teradata.jdbc.TeraDriver");
System.out.println(" JDBC driver loaded. \n");
con = DriverManager.getConnection(url, "<USER_ID>", "<PASSWORD>");
Statement stmt = con.createStatement();
System.out.println(" Statement object created. \n");
ResultSet rset = stmt.executeQuery(query);
//Some operations on resultset goes here...........
System.out.println(" total column count " + rset.getMetaData().getColumnCount());
} catch (Exception e) {
e.printStackTrace();
} finally {
// Close the statement
con.close();
System.out.println("\n Connection object closed. \n");
}
}
}
I am trying to figure out why my code is getting sent to the exception catch block and how to make this part of my log-in work correctly. The problem seems to be in Class.forName(driver); While debugging I noticed that I get an error, "variable source not available, source compiled with-out g-option". Is this the reason my code will not move onto the next step? if it is what do I need to fix it, and what does it mean?
I do have imported in my program.....
import java.sql.*;
import javax.swing.JOptionPane;
import java.sql.DriverManager;
private void SubmitActionPerformed(java.awt.event.ActionEvent evt) {
try {
String driver = "sun.jdbc.odbc.JdbcOdbcDriver";
Class.forName(driver);
String db = "jdbc:odbc:db1.mdb";
con = DriverManager.getConnection(db);
st = con.createStatement();
System.out.println("it actually ready this set of code!");
String un = UserName.getText().trim();
String pw = Password.getText().trim();
String sql = "select user,pass from Table2 where user='"+un+"'and pass='"+pw+"'";
rs=st.executeQuery(sql);
int count = 0;
while(rs.next()){
count = count+1;
}
if (count==1){
JOptionPane.showMessageDialog(null,"User, Found Access Granted!");
}
else if (count>1){
JOptionPane.showMessageDialog(null,"Duplicate User, Access Denied!");
}
else {
JOptionPane.showMessageDialog(null, "user doesn't exsist. ");
}
} catch (Exception ex){
System.out.println("exception 2 ");
}
// TODO add your handling code here:
}
Try removing .mdb from String db = "jdbc:odbc:db1.mdb";
and simply write String db = "jdbc:odbc:db1";
This might work for you!
Note this is gonna work on or below Java runtime 7 only
Since Java 8, the JDBC-ODBC Driver support has been removed. You can still do something like this to connect to MSAccess DB if you want.
Alternatively, you can use one of the many databases for which free JDBC drivers are available, like MySQL, PostgreSQL, SQLServer etc.
Get database connection object as below:
String database = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=db1.mdb;";
Connection conn = DriverManager.getConnection(database, "", "");
Also add code to print exception stack trace:
catch (Exception ex) {
System.out.println("exception 2 ");
ex.printStackTrace();
}
public class StudentDataPersistence {
public void insertStudentInfo(Student student) {
String url = "jdbc:oracle:thin:#localhost:1521:XE";
String username = "system";
String password = "Data03#";
Connection connection = null;
//Statement statement = null;
try {
//Step 1 : Register JDBC driver
Class.forName("oracle.jdbc.driver.OracleDriver");
//Step 2 : Open a connection
System.out.println("Connecting to a selected database...");
connection = DriverManager.getConnection(url, username, password);
if (connection != null) {
System.out.println("Connected to oracle");
}
//Step 3 : Write code to map Java Object to the Student_Info table
System.out.println("Inserting records into the database");
statement = connection.createStatement();
String sql = "insert into Student_Info " +
"VALUES(student.getName(),student.getRoll_no(),student.getAddress(),student.getPhone_no())";
statement.executeUpdate(sql);
System.out.println("Inserted student information into the database");
} catch (SQLException se) {
//handle errors for JDBC
se.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
//Handle errors for Class.forName
} finally {
System.out.println("Inside the finally block");
//finally block used to close resources
try {
statement.close();
} catch (SQLException se) {
se.printStackTrace();
}
try {
connection.close();
} catch (SQLException se) {
se.printStackTrace();
}
}
System.out.println("!GoodBye");
}
public static void main(String[] args) {
Student student = new Student("Bavin", 1, "Umar Nagar", "89898989809");
StudentDataPersistence obj = new StudentDataPersistence();
obj.insertStudentInfo(student);
}
}
The error it shows it :
Connecting to a selected database...
Connected to oracle
Inserting records into the database
java.sql.SQLException: ORA-00904: "STUDENT"."GETPHONE_NO": invalid identifier
at oracle.jdbc.dbaccess.DBError.throwSqlException(DBError.java:189)
at oracle.jdbc.ttc7.TTIoer.processError(TTIoer.java:242)
at oracle.jdbc.ttc7.Oall7.receive(Oall7.java:554)
at oracle.jdbc.ttc7.TTC7Protocol.doOall7(TTC7Protocol.java:1478)
at oracle.jdbc.ttc7.TTC7Protocol.parseExecuteFetch(TTC7Protocol.java:888)
at oracle.jdbc.driver.OracleStatement.executeNonQuery(OracleStatement.java:2076)
at oracle.jdbc.driver.OracleStatement.doExecuteOther(OracleStatement.java:1986)
at oracle.jdbc.driver.OracleStatement.doExecuteWithTimeout(OracleStatement.java:2697)
at oracle.jdbc.driver.OracleStatement.executeUpdate(OracleStatement.java:1035)
at org.core.hibernate.reason.StudentDataPersistence.insertStudentInfo(StudentDataPersistence.java:52)
at org.core.hibernate.reason.StudentDataPersistence.main(StudentDataPersistence.java:80)
Inside the finally block
!GoodBye
All the answers (those of you who illustrate it with an oracle query) in reply were wrong.
Kindly do have a look at it before posting.
the correct one i got when i posted another thread regarding the same:
String query = "insert into Student_Info(name,roll_no,address,phone_no) VALUES('"+student.getName()+"',"+student.getRoll_no()+",'"+student.getAddress()+"','"+student.getPhone_no()+"')";
you have commented out your Statement object definition. So the statement object is unknown when you're using it.
uncomment this line:
//Statement statement;
And as earlier pointed out by #putaro, you need to quote certain parts of your SQL query.
String sql = "insert into Student_Info " +
"VALUES("+student.getName()+","+student.getRoll_no()+","+student.getAddress()+","+student.getPhone_no()+")";
This is to insert the actual object values into the query. Things within the quote would be inserted as it is.
Error ORA-00904 means Oracle does not know the identifier "STUDENT"."GETPHONE_NO" it looks like you are trying to insert some value to a column named "GetPhone_NO" to Table "Student" from your SQL. so you should check your SQL and table structure again
I see there are two problems in the code.
Currently your code is not using the student object while making the query. All student.getName() etc call taken as plain strings rather than method calls that returns the appropriate values.
Second it would be better to write the query in the following form. It will avoid silly errors because of the structure of the tables.
"INSERT INTO student_info(name,roll_no,address,phone) VALUES("+
student.getName()+"," +
student.getRoll_no()+","+student.getAddress()+","+student.getPhone_no()+")";
Even better is if you use prepared statement like
Try changing the query like
"INSERT INTO student_info(name,roll_no,address,phone) VALUES(?,?,?,?)"
and then set the parameter values.