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.
Related
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
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
I'm creating my first Java program that pulls data from a MySql database. I'm having trouble getting the result from a query to print in console. My program compiles without error but out.print command not displaying content in console. I'm using Intellij IDEA 15.0.2.
import java.sql.*;
import static java.lang.System.*;
public class Main {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/animal";
String user = "username";
String pwd = "password";
try {
Connection connection =
DriverManager.getConnection(url, user, pwd); // Get Connection
Statement statement = connection.createStatement(); // Create Statement
String query = "SELECT * FROM animal";
ResultSet resultSet = statement.executeQuery(query); // Execute Query
while (resultSet.next()) { // Process Results
out.print(resultSet.getInt("animal_id"));
}
} catch (SQLException se) { }
}
}
To print out to console the correct command is
System.out.print("Whatever you want to print");
not
out.print("Whatever you want to print");
Yeah.. as BradStell said you have to use
System.out.print(resultSet.getInt("animal_id"));
instead of
out.print(resultSet.getInt("animal_id"));
Another suggestion that I would like to make is Always do something on catching an exception. You have no code in the catch block. Atleast try to print the exception there. That would help you very much in finding errors in your code .
The problem was with the database driver. I needed to use the forName method(), and add the driver url for MySql. After I successfully implemented this class I was able to create sql queries without issue. Thanks for the tip with the exception handling #Senthil Vidhiyakar
try {
Class.forName("com.mysql.jdbc.Driver");
System.out.print("Working");
}
catch (Exception e){ System.out.println("Not working");}
I also had to connect the mysql connector jar. The process for doing this in Intellij IDEA is as follows.
File >> Project Structure "The project structure window will appear then on the left side menu click Modules in the main content area click on the Dependencies tab. Next click the green +. Choose option 1 JARs or directories. Finally, navigate to the mysql connector jar. Then click apply, and ok."
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();
}
I am trying to connect java derby db and insert into a table. Everything goes ok but data is not inserted although there is no error at all. Cn you please let me know whats wrong? i tried to change the code and even created new database n table still same. Code works wihtout error but data is not inserted.
Here is my code
databasetest.java
package databasetest;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
public class DatabaseTest {
public static void main(String[] args) {
try{
Class.forName("org.apache.derby.jdbc.ClientDriver");
System.out.println(" class found " );
}catch(Exception e){
System.out.println("Not found driver class" + e);
};
try{
Connection conn = null;
String pass =null;
conn = DriverManager.getConnection("jdbc:derby://localhost:1527/user","APP",pass);
System.out.println(" Connected to database " );
try{
Statement st;
System.out.println(" inserted");
conn.close();
}catch(Exception e){
System.out.println(" Eror in inserting" + e );
}
}catch(Exception e){
System.out.println("Mistake happnd " + e);
}
}
}
here is run result
run:
class found
Connected to database
inserted
BUILD SUCCESSFUL (total time: 0 seconds)
Please can some one tell me whats going wrong?
Thanks in advance
The problem seems to reside here: Statement st;. You are creating a statement object but you are not associating any queries to it.
Please take a look at this Oracle Tutorial for more information on the matter.
Your code is not actually trying to insert anything.
Statement st;
System.out.println(" inserted");
conn.close();
This doesn't really do anything other than close the connection.
Usually you will want to create a PreparedStatement with a query like
PreparedStatement st = conn.prepareStatement("place your SQL Query here");
st.execute();
alternatively you could look into the API for PreparedStatement.
If you are set on using a regular Statement or your query is simple and does not involve insecure input, you can use
Statement stmt = conn.createStatement();
stmt.execute("Simple SQL Query here");
from the code looks like You have just created the connection with database.
there is no code to insert something into the database.
add the following code to insert some value into your database.
Statement stmt=con.createStatement();
String query="Insert into table_name values (comma separated sequential column value)"; //here comes your insertion query
ResultSet rs=stmt.executeQuery(query);