I'm trying to save a TextField value into a database but I get the error:
org.h2.jdbc.JdbcSQLException: Column count does not match; SQL statement:
INSERT INTO KIWI VALUES (104, ) [21002-173]
What I'd like to happen is to have a client's first name saved into the database when the 'addClient()' method is called.
Could anyone help me get it to work? Thank you all in advance.
I'm working in JavaFx and the 'TextField firstName' is being called from an FXML file that was created using JavaFx SceneBuilder. I've tried initializing it in the controller but no success. Any ideas? I thought these types of objects should not be innitialized, at least going by JavaFx rules as I understand.
The Controller Class:
import java.net.URL;
import java.sql.SQLException;
import java.util.ResourceBundle;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.TextField;
import wakiliproject.Forms.AddNew.DB.NewClientDB;
public class NewClientController implements Initializable {
#FXML
public TextField firstName;
// Initializes the controller class.
#Override
public void initialize(URL url, ResourceBundle rb) {
// TODO
}
#FXML
public void addClient() throws SQLException {
new NewClientDB().main();
}
}
The database class:
import Database.Plain.Skell.DBConnect;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import wakiliproject.Forms.AddNew.NewClientController;
public class NewClientDB extends NewClientController {
private String firstNames = new NewClientController().firstName.getText();
public void main() throws SQLException {
Connection conn = DBConnect.connect();
Statement stmt = null;
try {
//STEP 3: Open a connection
System.out.println("Connecting to a selected database...");
System.out.println("Connected database successfully...");
//STEP 4: Execute a query
System.out.println("Inserting records into the table...");
stmt = conn.createStatement();
String sql = "INSERT INTO KIWI "
+ "VALUES (104, " + (firstNames) + ")";
stmt.executeUpdate(sql);
System.out.println("Inserted records into the table...");
} 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
}
Edit:
I don't think the TextField values are being picked
As a sidenote, you should use PreparedStatements. You'll avoid concatenation errors as well as SQL injection.
But your problem seems to come from the fact that you're getting the value before the user has had a chance to type anything there. I'm not familiar with JavaFX, but your current code is getting the textfield value at the beginning of the program (when it's obviously still empty). Shouldn't it perform the addition when you click a button or something?
There are so many things wrong here.
You cannot create a new controller class with a new statement and expect it to be the same instance as that created by an FXMLLoader. Delete this line:
private String firstNames = new NewClientController().firstName.getText();
NewClientDB should not extend NewClientContoller. The FXMLLoader knows nothing about subclasses.
Pass the firstName from your controller to your NewClientDB instance.
new NewClientDB().main(firstName);
....
public void main(String firstNames)
Place single quotes around the firstNames string in your insert statement.
"INSERT INTO KIWI VALUES (104, '" + (firstNames) + "')";
Ensure that your KIWI table only has two columns with types compatible to your insert statement.
Check your FXML supplies an fx:id for firstName.
Check that you have a button defined in your FXML which triggers #addClient.
If the above doesn't solve your problem, edit your question to include your KIWI table DDL and your FXML file.
Related
I have a basic Java application (with a GUI) that uses a linked list to add/remove/modify Customer objects and I want to store them in a database (Oracle DB express to be exact)?
As I understand it, I have to create a table with some tool, and the use that tool to auto-generate a Java class that would allow me to communicate with the DB. How far off am I with this?
Just to make your question clear, What tool have you used to generate your java code?
I recommend you to avoid using code generation tool in case you want to learn in and out of Java.Here is an example of how you can connect your SWING application with Oracle DB,MySQL,Derby and many more other databases.
Connection con;
Statement smt;
ResultSet rs;
String user="databaseuser";
String pass="password";
String path="jdbc:oracle:thin:#localhost:1521:Sampledb"; //put db url here
try{
con=DriverManager.getConnection(path, user, pass);
smt=con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_UPDATABLE);
String SQL="SELECT *FROM Registered_users_tb "; //Your Query here
rs=smt.executeQuery(SQL);
rs.moveToInsertRow();
//First param is db column name,second param is variable name
rs.updateString("USERNAME", username);
rs.updateString("FNAME", fname);
rs.updateString("MNAME", mname);
rs.updateString("LNAME", lname);
rs.updateString("GENDER", gender);
rs.updateString("DEPARTMENT", dept);
rs.insertRow();
rs.close();
smt.close();
}
catch(SQLException err){
JOptionPane.showMessageDialog(Classname.this,err.getMessage());
}
For creating a complete new database, oracle provide a gui tool called DBCA. I found a couple of links to use this tool: Link 1 and Link 2
This tutorial teaches how to access an Oracle database. For accessing such an database you need additional drivers found here. Here an short example how to access such a database:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;
class DatabaseAccess
{
public static void main(String [] args)
{
Connection connection = null;
try
{
Class.forName("oracle.jdbc.OracleDriver");
String dbPath = "jdbc:oracle:thin:#localhost:1521:myDatabase";
String username = "user";
String password = "password";
connection = DriverManager.getConnection(dbPath, username, password);
if(connection != null)
{
System.out.println("Connected with database");
Statement statement = connection.createStatement();
ResultSet results = statementt.executeQuery("SELECT * FROM myTable");
while(result.next())
{
System.out.println(result.getString("myString"));
}
}
catch(ClassNotFoundException | SQLException exc)
{
exc.printStackTrace();
}
finally
{
try
{
connection.close();
}
catch(SqlException exc)
{
exc.printStackTrace();
}
}
}
}
For an more advanced example visit the given link.
create table query for department :
create table department
(
department_id tinyint(2) zerofill not null auto_increment,
department_name varchar(30) unique key,
department_description text,
primary key(department_id)
);
java code:
package hrmps;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import javax.swing.*;
class AddDepartment extends JPanel
{
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt)
{
String deptName=jTextField1.getText();
String deptDescription=jTextField2.getText();
Connection con=null;
PreparedStatement statement=null;
ResultSet rs=null;
String query="Insert into department values (?,?)";
try
{
Class.forName("com.mysql.jdbc.Driver");
con=DriverManager.getConnection("jdbc:mysql:///hrmps? zeroDateTimeBehavior=convertToNull","root","root");
statement=con.prepareStatement(query);
statement.setString(1,deptName);
statement.setString(2,deptDescription);
statement.execute();
int i=statement.executeUpdate();
if(i>0)
JOptionPane.showMessageDialog(null, "Record added");
else
JOptionPane.showMessageDialog(null, "Record couldn't be added");
con.close();
}
catch(Exception ex)
{
System.out.println(ex.getMessage());
}
} //end of method
}//end of class
String deptName=jTextField1.getText();
String deptDescription=jTextField2.getText();
Those two statements are out of any method. So they're executed when the object is constructed, well before the user has any chance to type anything in the text fields.
Make those local variables of the jButton1ActionPerformed method. It's only when the button is clicked that you must read what the text fields contain.
BTW, all the fields in the posted code should be local variables. And your method isNullOrEmpty returns false when the argument is null or empty. That's very confusing.
my code is given below and i hav created a user class also
package com.glomindz.mercuri.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import com.glomindz.mercuri.pojo.User;
import com.glomindz.mercuri.util.MySingleTon;
public class UserServicesDAO {
private Connection connection;
public UserServicesDAO() {
// connection = new MySingleTon().getConnection();
connection = MySingleTon.getInstance().getConnection();
}
public List<User> get_all_data() {
List<User> usersList = new ArrayList<User>();
String query = "SELECT * FROM spl_user_master";
try {
PreparedStatement stmt = connection.prepareStatement(query);
boolean execute = stmt.execute();
System.out.println(execute);
ResultSet resultSet = stmt.getResultSet();
System.out.println(resultSet.getMetaData());
while (resultSet.next()) {
User user = new User();
user.setId(resultSet.getInt("id"));
user.setName(resultSet.getString("name"));
user.setEmail(resultSet.getString("email"));
user.setMobile(resultSet.getString("mobile"));
user.setPassword(resultSet.getString("password"));
user.setRole(resultSet.getString("role"));
user.setStatus(resultSet.getString("status"));
user.setLast_udpate(resultSet.getString("last_update"));
// print the results
System.out.println(user);
usersList.add(user);
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
public static void main(String[] args) {
new UserServicesDAO().get_all_data();
}
}
i got the output, only last_update gives me null value. I have changed it to timestamp but no effect...in the debug gives me error:
Thread main suspended
UserServicesDAO.get_all_data() line24
UserServicesDAO.main(String[]) line56
what's the problem plz give me a solution..
I see only two reasons for user.last_update to be null:
It's null in the database. Check your data. Check that everything is committed. Check that you're querying the correct database.
setLast_update() doesn't actually set the field last_update field. Show us the code of User to confirm or infirm.
Also, please respect the Java naming conventions.
I think the problem is with your database. Make sure resultSet is returning the right type.
For example:
resultSet.getInt("id");
might be
resultSet.getLong("id");
this can cause you troubles. At least this happened to me once. You should check for other fields name,email,mobile.
Also be careful about date
resultSet.getString("last_update")
if in your database "last_update" column type is not string, this can also cause you problems
I have created a simple Java connection script in Java to connect to a database shown below.
import java.sql.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
public class dbconn {
public static void main(String[] args) throws ClassNotFoundException
{
Class.forName("org.sqlite.JDBC");
Connection connection = null;
try
{
// create a database connection
connection = DriverManager.getConnection("jdbc:sqlite:C:/Program Files (x86)/Spiceworks/db/spiceworks_prod.db");
Statement statement = connection.createStatement();
statement.setQueryTimeout(30); // set timeout to 30 sec.
}
catch(SQLException e)
{
// if the error message is "out of memory",
// it probably means no database file is found
System.err.println(e.getMessage());
}
finally
{
try
{
if(connection != null)
connection.close();
}
catch(SQLException e)
{
// connection close failed.
System.err.println(e);
}
}
}
}
Now I have tested this connection via some SQL queries inside the dbconn script and it works.
However my question is, how would Icall this instance of the database into another form in the same project to preform the same SQL queries which are:
ResultSet resultSet = null;
resultSet = statement.executeQuery("SELECT * FROM users");
while (resultSet.next())
{
System.out.println("EMPLOYEE Email: " + resultSet.getString("email"));
}
You can retain and reuse the Connection, saving it probably in some static field. If you access it from multiple threads, SQLite must work in the Serialized mode. You must have the code somewhere to re-establish the connection if it has been lost for some reason.
If the use of Connection is not heavy, you can also have some method that opens it and close when no longer needed, better inside the finally block.
package database;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import database.Dbconnect;
public class CreateQuery {
Connection conn;
public CreateQuery() throws ClassNotFoundException, SQLException, IOException {
conn=new Dbconnect().returnDatabaseConnection();
}
public int addNewLayertoDB(String feature_name,String shape,int Latitude , int Longitude , int feature_geom , String feature_details){
try {
PreparedStatement statement = null;
String table_name = feature_name + "_" + shape;
String query = "CREATE TABLE EtherMap "+table_name+" ("+ feature_name+" (20))";
statement = conn.prepareStatement(query);
statement.setString(1, feature_name);
statement.execute();
String squery = "ALTER TABLE EtherMap" +table_name+" ADD COLUMN geom int , ADD COLUMN shape character(10)";
return 1;
} catch (SQLException ex) {
return 0;
}
}
public void closeConn() throws SQLException {
if (conn != null) {
this.conn.close();
}
}
}
I have coded this createquery.java code which would create a table in postgres . I need to call it when I draw anything on a open layers map , using javascript in a jsp page . How do I call it ? Do I have to use the beans ?
It would be good design if you call it from servlet and servlet from jsp taking user input
See Also
Servlet
Make a request to your server, on a specific URL, probably using JavaScript
Map that URL to a specific Servlet
Code your servlet to execute whatever method, you like, of your class
Simple, isn't it?