java.sql.SqlException: no data found while inserting the data into table - java

I am trying to inserting the data into the table using ms access 2007 but getting the exception "java.sql.SqlException: no data found"
My data souce name is employee
import java.sql.*;
class AccessDatabase
{
public static void main(String[] args)
{
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con = DriverManager.getConnection ("jdbc:odbc:employee");
Statement st = con.createStatement();
String name = "roseindia";
String address = "delhi";
int i = st.executeUpdate("insert into user(name,address) values
('" + name + "','" + address + "')");
System.out.println("Row is added");
}
catch (Exception e)
{
System.out.println(e);
}
}
}

I think you don't have a database created. Following code should work:
import java.sql.*;
class ExecuteSqlQuery {
public static void main(String[] args) {
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "root");
Statement st=con.createStatement();
String str = "CREATE TABLE user(id INTEGER, " + "name VARCHAR(25), address VARCHAR(100), primary key(id))";
st.executeUpdate(str);
System.out.println("Table is created into the database.");
st.executeUpdate("insert into user(id,name,address) values(1111,'roseindia','Rohini,Delhi')");
System.out.println("Row is inserted.");
st.close();
con.close();
}
catch (Exception ex) {
System.out.println("Unable to connect to database.");
}
}
}

Related

how do i resolve this java.lang.NullPointerException?

i am trying to run app that runs on both hsql and mysql database, to when i run it i get this error :
java.lang.NullPointerException: Cannot invoke "java.sql.Connection.prepareStatement(String)" because "this.cnn" is null
at DataBase.DBcontrol.creer_piece(DBcontrol.java:122)
at pdr.FrontController.initialize(FrontController.java:160)
at javafx.fxml/javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2573)
at javafx.fxml/javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2466)
at javafx.fxml/javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3237)
at javafx.fxml/javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3194)
at javafx.fxml/javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3163)
at javafx.fxml/javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3136)
at javafx.fxml/javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3113)
at javafx.fxml/javafx.fxml.FXMLLoader.load(FXMLLoader.java:3106)
at pdr.Main.start(Main.java:13)
at javafx.graphics/com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$9(LauncherImpl.java:846)
at javafx.graphics/com.sun.javafx.application.PlatformImpl.lambda$runAndWait$12(PlatformImpl.java:455)
at javafx.graphics/com.sun.javafx.application.PlatformImpl.lambda$runLater$10(PlatformImpl.java:428)
at java.base/java.security.AccessController.doPrivileged(AccessController.java:391)
at javafx.graphics/com.sun.javafx.application.PlatformImpl.lambda$runLater$11(PlatformImpl.java:427)
at javafx.graphics/com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:96)
at javafx.graphics/com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at javafx.graphics/com.sun.glass.ui.win.WinApplication.lambda$runLoop$3(WinApplication.java:174)
at java.base/java.lang.Thread.run(Thread.java:832)
the chunck of code its reffering to in the first few lines are these :
public void creer_piece() throws ClassNotFoundException {
HConnexion dbc = new HConnexion(); cnn=dbc.connectDb();
PreparedStatement pss;
ResultSet s;
try {
req = "CREATE TABLE IF NOT EXISTS moussa.piece "
+ " (id VARCHAR(30), "
+ " atelier VARCHAR(30), "
+ " piece VARCHAR(30), "
+ " type VARCHAR(30) NULL, "
+ " pa VARCHAR(2) NULL, "
+ " ref1 VARCHAR(10) NULL , "
+ " ref2 VARCHAR(10) NULL , "
+ " quant INTEGER,"
+ " emp VARCHAR(30),"
+ " pos VARCHAR(30),"
+ " UNIQUE (id))";
pss = cnn.prepareStatement(req);
int e = pss.executeUpdate();
if (e > 0) {
JOptionPane.showMessageDialog(null, " erraurgg");
}
} catch (SQLException ex) {
JOptionPane.showMessageDialog(null, ex);
}
and this one :
public void initialize(URL url, ResourceBundle rb) {
try {
run_wamp();
timer.schedule(new TimerTask() {
#Override
public void run() {
}
},10000);
dbc.creer_piece();dbc.creer_refs();dbc.creer_carte();dbc.creer_module();dbc.creer_eqip();
dbc.creer_c8();dbc.creer_secteur();dbc.creer_unite();dbc.creer_eqip();
dbc.creer_atelier();
dbc.get_natelier("SELECT * FROM moussa.atelier",combo_piece1);
} catch (Exception ex) {
Logger.getLogger(FrontController.class.getName()).log(Level.SEVERE, null, ex);
}
i think it has to do with my database, either the app is not creating the tables or i should create the tables manually and connect them, though i am just spit balling here, need some help please.
edit: so after looking at the comments, you guys told me that cnn is returning null because of the connectDB well here it is:
public class HConnexion {
private static String msg ;
Connection conn = null;Statement stm =null;
//=====================================================================================
public Connection connectDb() throws ClassNotFoundException {
String s = System.getProperty("user.home");
String JDBC_URL = "jdbc:hsqldb:Pdr_db;";
run_wamp();
String path= "jdbc:mysql://localhost:3306/mysql?zeroDateTimeBehavior=convertToNull";
try {
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection(JDBC_URL, "root", ""); //hsql database
conn = DriverManager.getConnection(path, "root", ""); //mysql database
stm=conn.createStatement();
stm.executeUpdate("create database IF NOT EXISTS moussa ");
return conn;
} catch (SQLException e) {
JOptionPane.showMessageDialog(null, e);
return null;
}
}
this method (correct me if i am wrong) is supposed to connect me to my database (or create a new one in case there isn't any), so if cnn is returning null, does that mean that its not creating a database which the other methods can connect through cnn.
The null pointer exception is caused by your incorrect connection code which returns null.
// code for HSQLDB
public class HConnexion {
private static String msg = "Cannot connect";
Connection conn = null;Statement stm =null;
public Connection connectDb() throws ClassNotFoundException, SQLException {
String s = System.getProperty("user.home");
String JDBC_URL = "jdbc:hsqldb:Pdr_db;"; // this is a HSQLDB URL
run_wamp();
// String path= "jdbc:mysql://localhost:3306/mysql?zeroDateTimeBehavior=convertToNull"; // we leave this out as you can connect only to one database, not two
try {
Class.forName("org.hsqldb.jdbc.JDBCDriver");
// Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(JDBC_URL, "root", ""); //hsql database - used
// conn = DriverManager.getConnection(path, "root", ""); //mysql database - unused
stm=conn.createStatement();
// stm.executeUpdate("create database IF NOT EXISTS moussa "); // only for mysql
return conn;
} catch (SQLException e) {
JOptionPane.showMessageDialog(msg, e);
throw e;
}
}
If you want to connect to MySQL, use this code
// code for MySQL
public class HConnexion {
private static String msg = "Cannot connect";
Connection conn = null;Statement stm =null;
public Connection connectDb() throws ClassNotFoundException, SQLException {
String s = System.getProperty("user.home");
// String JDBC_URL = "jdbc:hsqldb:Pdr_db;"; // this is a HSQLDB URL
run_wamp();
String path= "jdbc:mysql://localhost:3306/mysql?zeroDateTimeBehavior=convertToNull"; // we use this for MySQL
try {
// Class.forName("org.hsqldb.jdbc.JDBCDriver");
Class.forName("com.mysql.jdbc.Driver");
// conn = DriverManager.getConnection(JDBC_URL, "root", ""); //hsql database - unused
conn = DriverManager.getConnection(path, "root", ""); //mysql database - used
stm=conn.createStatement();
stm.executeUpdate("create database IF NOT EXISTS moussa "); // only for mysql
return conn;
} catch (SQLException e) {
JOptionPane.showMessageDialog(msg, e);
throw e;
}
}

Why doesn't my Java code create a table in an in-memory SQLite database and print the table name?

I want to create an in-memory database and check that the table exists afterwards. Unfortunately, my code doesn't print anything to the console, so either the check for a table or the table creation process is wrong.
How do I fix it?
import java.sql.*;
public class Main {
private static String url = "jdbc:sqlite::memory";
private static void createNewTable(Connection conn) {
String sql = "CREATE TABLE IF NOT EXISTS students (\n"
+ " id integer PRIMARY KEY,\n"
+ " name text NOT NULL"
+ ");";
try (Statement stmt = conn.createStatement();) {
stmt.execute(sql);
} catch (SQLException e) {
System.out.println(e.getMessage());
}
}
private static void checkTable(Connection conn){
String sql = "SELECT name FROM sqlite_temp_master WHERE type='table'";
try (Statement stmt = conn.createStatement();) {
ResultSet rs = stmt.executeQuery(sql);
while (rs.next()) {
System.out.println("table: " + rs.getString(1));
}
} catch (SQLException e) {
System.out.println(e.getMessage());
}
}
public static void main(String[] args) {
Connection conn;
try{
conn = DriverManager.getConnection(url);
createNewTable(conn);
checkTable(conn);
} catch (SQLException e) {
System.out.println(e.getMessage());
}
}
}

Java - How can I INSERT values in SQLite?

Im starting in SQLite, I created my db and the connection works.
When I try to Insert a value (the db is empty) I get the following error:
java.sql.SQLException: near ".684": syntax error
import java.sql.*;
public class connection{
String route = "C:\\Freeman SA.db";
Connection c = null;
Statement stat = null;
String op;
public void connect(){
try{
c = DriverManager.getConnection("jdbc:sqlite:"+route);
if (c!=null)
System.out.println("Connected to db.");
}
catch (SQLException ex) {
System.err.println("Couldn't connect."+ex.getMessage());
}
}
public void insert_DB(String NAME, String LNAME, String ID, int AGE, int TIME, int SALARY) throws SQLException{
connect();
try {
stat = c.createStatement();
op = "INSERT INTO Remuneraciones (Nombre, Apellido, Rut, Edad, Tiempo, Sueldo) VALUES (" + NAME + ", " + LNAME + ", " + ID + ", " + AGE + ", " + TIME + ", " + SALARY + ");";
stat.executeUpdate(op); //Here is the problem
stat.close();
}
catch (SQLException e) {
System.err.println(e.getClass().getName() + ": " + e.getMessage());
}
c.close();
}
}
Main.
public static void main(String[] args) throws IOException {
connection n = new connection();
try {
n.insert_DB("Charlie", "White", "18.954.621-K", 21, 2, 650000);
} catch (SQLException ex) {
Logger.getLogger(main.class.getName()).log(Level.SEVERE, null, ex);
}
}
PD: I'm learning from here: http://www.tutorialspoint.com/sqlite/sqlite_java.htm
It's a bad idea to create a SQL statement by concatenating Strings like that. Do some research into SQL injection attack and Little Bobby Tables.
PreparedStatement is a better idea. Bind your variables after validation.
See if this makes your life better:
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
/**
* Demo RenumerationDao
* Created by Michael
* Creation date 6/8/2016.
* #link https://stackoverflow.com/questions/37714254/java-how-can-i-insert-values-in-sqlite/37714292#37714292
*/
public class RenumerationDao {
private static final String INSERT_SQL = "INSERT INTO Remuneraciones(Nombre, Apellido, Rut, Edad, Tiempo, Sueldo) VALUES(?, ?, ?, ?, ?, ?)";
private Connection connection; // Better to get this from a pool.
public RenumerationDao(Connection connection) {
this.connection = connection;
}
public int insert(String firstName, String lastName, String id, int age, int timeInHours, int salary) {
int numRowsInserted = 0;
PreparedStatement ps = null;
try {
ps = this.connection.prepareStatement(INSERT_SQL);
ps.setString(1, firstName);
ps.setString(2, lastName);
ps.setString(3, id);
ps.setInt(4, timeInHours);
ps.setInt(5, age); // You'll have to update this each and every year. BirthDate would be better.
ps.setInt(6, salary);
numRowsInserted = ps.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
} finally {
close(ps);
}
return numRowsInserted;
}
public static void close(Statement statement) {
try {
if (statement != null) {
statement.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}

How to start Derby server on the specified port by java

I tried to test Derby sample source code. Unfortunately it failed: Cannot connect Derby database: connection refused
I was told that I haven't started a server. Official tutorial:
Doesn't start any server.I have no feedback after C:\Apache\db-derby-10.4.1.3-bin\lib> java -jar derbyrun.jar server start just empty line shows and the derbyrun.jar ends.
Doesn't show how to create server on the specified port
My question is: How to start a server on the specified port so the posted code works:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.ResultSetMetaData;
public class Restaurants
{
private static String dbURL = "jdbc:derby://localhost:1526/myDB;create=true;user=me;password=mine";
private static String tableName = "restaurants";
// jdbc Connection
private static Connection conn = null;
private static Statement stmt = null;
public static void main(String[] args)
{
createConnection();
insertRestaurants(5, "LaVals", "Berkeley");
selectRestaurants();
shutdown();
}
private static void createConnection()
{
try
{
Class.forName("org.apache.derby.jdbc.ClientDriver").newInstance();
//Get a connection
conn = DriverManager.getConnection(dbURL);
}
catch (Exception except)
{
except.printStackTrace();
}
}
private static void insertRestaurants(int id, String restName, String cityName)
{
try
{
stmt = conn.createStatement();
stmt.execute("insert into " + tableName + " values (" +
id + ",'" + restName + "','" + cityName +"')");
stmt.close();
}
catch (SQLException sqlExcept)
{
sqlExcept.printStackTrace();
}
}
private static void selectRestaurants()
{
try
{
stmt = conn.createStatement();
ResultSet results = stmt.executeQuery("select * from " + tableName);
ResultSetMetaData rsmd = results.getMetaData();
int numberCols = rsmd.getColumnCount();
for (int i=1; i<=numberCols; i++)
{
//print Column Names
System.out.print(rsmd.getColumnLabel(i)+"\t\t");
}
System.out.println("\n-------------------------------------------------");
while(results.next())
{
int id = results.getInt(1);
String restName = results.getString(2);
String cityName = results.getString(3);
System.out.println(id + "\t\t" + restName + "\t\t" + cityName);
}
results.close();
stmt.close();
}
catch (SQLException sqlExcept)
{
sqlExcept.printStackTrace();
}
}
private static void shutdown()
{
try
{
if (stmt != null)
{
stmt.close();
}
if (conn != null)
{
DriverManager.getConnection(dbURL + ";shutdown=true");
conn.close();
}
}
catch (SQLException sqlExcept)
{
}
}
}
Setting port numbers
By default, Derby using the Network Server listens on TCP/IP port number 1527. If you want to use a different port number, you can specify it on the command line when starting the Network Server. For example:
java org.apache.derby.drda.NetworkServerControl start -p 1088
However, it is better to specify the port numbers by using any of the following methods
1. Change the startNetworkServer.bat or startNetworkServer.ksh scripts
2. Use the derby.drda.portNumber property in derby.properties
Please refer to:
https://db.apache.org/derby/docs/10.5/adminguide/tadminappssettingportnumbers.html

Querying a database via a constructor

I'm really hopping some help from anyone who would be kind enough to help me resolve this. I've been at it since yesterday.
See, what I'm trying to do is create a database query class that I can re-use over and over again as many times as possible without having to write a query every other time I need to search or display items from the database.
I'd like to be able to pass the query specifications via a constructor.
I however, get this error:
run:
Connecting to a selected database...
Connected database successfully...
Creating statement...
org.h2.jdbc.JdbcSQLException: Data conversion error converting ; SQL statement:
This is my code so far:
import java.sql.*;
public class RsToAList {
private final String table;
private final String columns;
private final String whereColumn;
private final String equalsEntry;
public RsToAList (String columns, String table, String whereColumn, String equalsEntry) {
this.table = table;
this.columns = columns;
this.whereColumn = whereColumn;
this.equalsEntry = equalsEntry;
}
// JDBC driver name and database URL
static String JDBC_DRIVER = "org.h2.Driver";
static String DB_URL = "jdbc:h2:file:C:/tryDb/tryDb";
// Database credentials
static String USER = "sa";
static String PASS = "";
public static void main (String[] args) {
RsToAList tryAndGet = new RsToAList("fullNames", "CLIENT", "postOfficeBoxNumber", "6448");
tryAndGet.ourQueryMethod();
}
public void ourQueryMethod () {
Connection conn = null;
Statement stmt = null;
try {
// STEP 2: Register JDBC driver
Class.forName(getJDBC_DRIVER());
// STEP 3: Open a connection
System.out.println("Connecting to a selected database...");
conn = DriverManager.getConnection(getDB_URL(), getUSER(), getPASS());
System.out.println("Connected database successfully...");
// STEP 4: Execute a query
System.out.println("Creating statement...");
stmt = conn.createStatement();
String sql = "SELECT " + (columns) + " FROM " + (table) + " WHERE "+ (whereColumn) +" = "+ (equalsEntry) +"";
ResultSet rs = stmt.executeQuery(sql);
//STEP 5: Extract data from result set
while (rs.next()) {
// Retrieve by column name
String first = rs.getString(columns);
// Display values
System.out.print("ID: " + first);
}
rs.close();
} 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
System.out.println("Goodbye!");
} // end main
/**
* #return the JDBC_DRIVER
*/
public static String getJDBC_DRIVER() {
return JDBC_DRIVER;
}
/**
* #param aJDBC_DRIVER the JDBC_DRIVER to set
*/
public static void setJDBC_DRIVER(String aJDBC_DRIVER) {
JDBC_DRIVER = aJDBC_DRIVER;
}
/**
* #return the DB_URL
*/
public static String getDB_URL() {
return DB_URL;
}
/**
* #param aDB_URL the DB_URL to set
*/
public static void setDB_URL(String aDB_URL) {
DB_URL = aDB_URL;
}
/**
* #return the USER
*/
public static String getUSER() {
return USER;
}
/**
* #param aUSER the USER to set
*/
public static void setUSER(String aUSER) {
USER = aUSER;
}
/**
* #return the PASS
*/
public static String getPASS() {
return PASS;
}
/**
* #param aPASS the PASS to set
*/
public static void setPASS(String aPASS) {
PASS = aPASS;
}
}
I'm a JAVA/ Programming newbie, and I'm trying to teach myself how to code from home in case my question seems too simple, or I seem to have overlooked something in my code.
Edit:
I'm not sure if this could help you help me, but this is the class that creates the database table:
//STEP 1. Import required packages
import java.sql.*;
public class JDBCExampleCreateTables {
// JDBC driver name and database URL
private static String JDBC_DRIVER = "org.h2.Driver";
private static String DB_URL = "jdbc:h2:file:C:/tryDb/tryDb";
// Database credentials
private static String USER = "sa";
private static String PASS = "";
public static void main (String[] args) {
Connection conn = null;
Statement stmt = null;
try {
//STEP 2: Register JDBC driver
Class.forName(JDBC_DRIVER);
//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 CLIENT " +
"(ID INT UNSIGNED NOT NULL AUTO_INCREMENT, " +
" fullNames VARCHAR(255), " +
" iDNumber VARCHAR(255), " +
" pINNumber VARCHAR(255), " +
" passportNumber VARCHAR(255), " +
" postOfficeBoxNumber VARCHAR(255), " +
" postalCode VARCHAR(255), " +
" telephoneNumberLandline VARCHAR(255), " +
" telephoneNumberMobile VARCHAR(255)) ";
stmt.executeUpdate(sql);
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
System.out.println("Goodbye!");
} // end main
} // end
Looks like a error in your sql statement.Make sure the data type you are comparing is compatible.PreparedStatement is handy instead of concatenating queries.
PreparedStatement stm = conn.prepareStatement("select * from person where name=?");
stm.setString(1,"ABC");
ResultSet rs= stm.executeQuery();
Although you have not shared the column type for the where condition. But most proabably you may be passing a string value to where clause but not enclosing it in single quotes:
String sql = "SELECT " + (columns) + " FROM " + (table) + " WHERE "+ (whereColumn) +" = "+ (equalsEntry) +"";
change it to:
String sql = "SELECT " + (columns) + " FROM " + (table) + " WHERE "+ (whereColumn) +" ='"+ (equalsEntry) +"'";
The other potential candidate for defect is this statementn:
String first = rs.getString(columns);
It may throw an error if any of your column type is not VARCHAR

Categories