I am using a video course on database programming with the current lesson being using Java to connect to MySQL. I have followed the video, and even copied the text working file for this particular problem (so I know the code works), but I am still getting an error. The database is to store information for books: isbn, title, author, publisher, and price. I inserted the exact same data using the command line, but when I use the program for a GUI I get a "data truncated" error. I know there are multiple answers in "data truncated" errors; however, I do not see where the data is too large, especially when inserting works using a non GUI interface. All datatypes are VARCHAR except for price which is FLOAT. The error I get is:
insert into book values('978007106789','Stuck On Java','J Reid','9.99','Osborne')
Error executing SQL
java.sql.SQLException: Data truncated for column 'price' at row 1
GUI code is:
package Connection;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.sql.*;
import java.util.*;
public class InsertRecord extends JFrame {
private JButton getBookButton, insertBookButton;
private JList bookList;
private Connection connection;
private JTextField isbn, title, author, price, publisher;
private JTextArea errorText;
public InsertRecord() {
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
}
catch (Exception e) {
System.err.println("Unable to load driver.");
System.exit(1);
}
}
public void loadBook() {
Vector<String> v = new Vector<String>();
try {
Statement statement = connection.createStatement();
ResultSet rs = statement.executeQuery("select title from book");
while (rs.next()) {
v.addElement(rs.getString("title"));
}
rs.close();
}
catch (SQLException e) {
System.err.println("Error executing SQL");
}
bookList.setListData(v);
}
private void createGUI() {
Container c = getContentPane();
c.setLayout(new FlowLayout());
bookList = new JList();
loadBook();
bookList.setVisibleRowCount(2);
JScrollPane bookListScrollPane = new JScrollPane(bookList);
getBookButton = new JButton("Get Book Title");
getBookButton.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e) {
String query = "select * from book where title = " +
bookList.getSelectedValue();
try {
Statement statement = connection.createStatement();
ResultSet rs = statement.executeQuery(
"select * from book where title = '"
+ bookList.getSelectedValue() + "'");
/*ResultSet rs = statement.executeQuery(
"select * from book where title = 'Java:How To Program'"); */
if (rs.next()) {
isbn.setText(rs.getString("isbn"));
title.setText(rs.getString("title"));
author.setText(rs.getString("author"));
price.setText(rs.getString("price"));
publisher.setText(rs.getString("publisher"));
}
}
catch (SQLException ex) { isbn.setText(query); }
}
}
);
insertBookButton = new JButton("Insert Book");
insertBookButton.addActionListener (
new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
Statement statement = connection.createStatement();
String insert = "insert into book values(";
insert += "'" + isbn.getText() + "',";
insert += "'" + title.getText() + "',";
insert += "'" + author.getText() + "',";
insert += "'" + price.getText() + "',";
insert += "'" + publisher.getText() + "')";
System.out.println(insert);
/*int i = statement.executeUpdate("insert into book values(" +
"'" + isbn.getText() + "'," +
"'" + title.getText() + "'," +
"'" + author.getText() + "'," +
"'" + price.getText() + "'," +
"'" + publisher.getText() + ")");*/
int i = statement.executeUpdate(insert);
errorText.append("Inserted " + i + " rows succcessfully.");
bookList.removeAll();
loadBook();
}
catch (SQLException ex) {
System.err.println("Error executing SQL");
ex.printStackTrace();
}
}
}
);
JPanel first = new JPanel(new GridLayout(3,1));
first.add(bookListScrollPane);
first.add(getBookButton);
first.add(insertBookButton);
isbn = new JTextField(13);
title = new JTextField(50);
author = new JTextField(50);
price = new JTextField(8);
publisher = new JTextField(50);
errorText = new JTextArea(5,15);
errorText.setEditable(false);
JPanel second = new JPanel();
second.setLayout(new GridLayout(6,1));
second.add(isbn);
second.add(title);
second.add(author);
second.add(price);
second.add(publisher);
JPanel third = new JPanel();
third.add(new JScrollPane(errorText));
c.add(first);
c.add(second);
c.add(third);
setSize(800, 400);
setVisible(true);
}
public void connectToDB() throws Exception {
//Connection conn = null;
try {
String userName = "jesse";
String password = "password";
String url = "jdbc:mysql://localhost/library";
Class.forName("com.mysql.jdbc.Driver").newInstance();
connection = DriverManager.getConnection(url, userName, password);
//if (conn != null) System.out.println("Database connection successful.");
}
catch (SQLException e) {
System.out.println("Can't connect to database");
System.exit(1);
}
}
private void init() throws Exception{
connectToDB();
}
public static void main(String[] args) throws Exception {
InsertRecord insert = new InsertRecord();
insert.addWindowListener(
new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
}
);
insert.init();
insert.createGUI();
}
}
The insert code for simply using the command line is:
package Connection;
import java.sql.*;
import java.io.*;
public class InsertDB {
Connection connection;
public InsertDB(){
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
}
catch (Exception e) {
System.out.println("Could not load driver.");
e.printStackTrace();
}
}
public void ConnectToDB() {
try {
connection = DriverManager.getConnection("jdbc:mysql://localhost/library", "jesse", "password");
System.out.println("Connected to database.");
}
catch (Exception e) {
System.out.println("Cannot connect to database.");
e.printStackTrace();
}
}
public void execSQL() {
try {
Statement stmt = connection.createStatement();
BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter the isbn: ");
String isbn = input.readLine();
System.out.print("Enter the title: ");
String title = input.readLine();
System.out.print("Enter the author: ");
String author = input.readLine();
System.out.print("Enter the publisher: ");
String pub = input.readLine();
System.out.print("Enter the price: ");
String p = input.readLine();
double price = Double.parseDouble(p);
String insert = "Insert into book values (" + "'" + isbn + "','" + title + "','" + author + "','" + pub + "'," + price + ")";
System.out.println(insert);
int inserted = stmt.executeUpdate(insert); //returns 1 for success, 0 for failure
if (inserted > 0) {
System.out.println("Successfully inserted " + inserted + " row.");
}
}
catch (Exception e) {
System.out.println("Error executing SQL");
e.printStackTrace();
}
}
public static void main(String[] args){
InsertDB conn = new InsertDB();
conn.ConnectToDB();
conn.execSQL();
}
}
The only differences I have noticed is price being in quotes in the GUI code; however, removing the quotes simply causes the same error without quotes. Also I noticed that the GUI code sets price to 8 bits (original code was 10), whereas, float is not set to anything in MySQL (I believe I read on another post it is 8 bits by default... which is why I used 8). I reached out to the author of the video and he suggested I remove the quotes surrounding price. But as I stated this did not help... also this code was copied from his working file that worked on the video. Any help is appreciated.
Database code is:
drop table book;
create table book (
isbn_13 varchar(13) primary key,
title varchar(50),
author varchar(50),
publisher varchar(50),
price float(11)
);
Starting again from scratch I completely dropped the book table then recreated it using the MySQL code above. After recreating the table I was able to insert using the GUI code. I am not sure what the cause of my problem was, but dropping and recreating the table seemed to fix it.
Related
i have problem with my project, and it still new for me with MYSQL, i want to get data from database and do some calculation and update the value on it,
its like making withdraw function like ATM machine. This my table look like.
enter image description here . You can see constructor parameter that carry value (String value and String ID). For Value="100"; and ID="5221311" you can see it on my table picture.
public ConformWithdraw() {
initComponents();
try {
Class.forName("com.jdbc.mysql.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:/atm", "root", "");
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
public ConformWithdraw(String value,String ID) {
initComponents();
this.value=value;
this.ID=ID;
}
------------------------------------------------------------
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
try {
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/atm?zeroDateTimeBehavior=convertToNull", "root", "");
String validate = "SELECT * FROM customer_details WHERE accountID LIKE '" + ID
+ "'";
PreparedStatement smtm = con.prepareStatement(validate);
ResultSet resultSet = smtm.executeQuery();
User user = null;
if (resultSet.next()) {
user = new User();
user.setBalance(resultSet.getString("accountBalance"));
double balance=Double.parseDouble(user.getBalance());
double val=Double.parseDouble(value);
total =(balance - val);
}
smtm.close();
resultSet.close();
program();
} catch (SQLException | HeadlessException | ClassCastException ex) {
JOptionPane.showMessageDialog(null, ex);
}
}
-------------------------------------------------------------
public void program(){
String sqlUpdate = "UPDATE customer_details "
+ "SET accountBalance = '"+String.valueOf(total)+"'"
+ "WHERE accountID = '"+ID+"'";
try{
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/atm?zeroDateTimeBehavior=convertToNull", "root", "");
PreparedStatement pstmt = con.prepareStatement(sqlUpdate);
id=Integer.parseInt(ID);
pstmt.setString(1, String.valueOf(total));
pstmt.setInt(2, id);
int rowAffected = pstmt.executeUpdate();
pstmt.close();
new ShowWithdraw().setVisible(true);
dispose();
}catch(SQLException | HeadlessException | ClassCastException ex){
JOptionPane.showMessageDialog(null, ex);
JOptionPane.showMessageDialog(null, "slh sini");
}
}
You are already setting the parameters on the query, so It tries to set the parameters and find no parameters to find. Try this:
String sqlUpdate = "UPDATE customer_details "
+ "SET accountBalance = ?"
+ "WHERE accountID = ?";
So i try to create a JTable which connect to SQL server database by JBDC, and have a function like insert, delete, and edit the data. It work well with insert but update, delete. Can you guys show me why i got ArrayIndexOutOfBoundsException: -1 and how to fix it. Here 's my code. Book here is a class extends JFRAME
public Book() {
initComponents();
model.addColumn("ID");
model.addColumn("Name");
model.addColumn("Type");
jTable1.setModel(model);
displayTable();
jTable1.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
#Override
public void valueChanged(ListSelectionEvent e) {
int row = jTable1.getSelectedRow();
txtName.setText(jTable1.getValueAt(row, 1).toString());
txtType.setText(jTable1.getValueAt(row, 2).toString());
}
});
}
public void displayTable() {
try {
model.setRowCount(0);
ConnectToSQL sql = new ConnectToSQL();
connection = sql.getConnection();
st = connection.createStatement();
ResultSet result = st.executeQuery("SELECT * FROM BOOK");
while (result.next()) {
model.addRow(new Object[]{result.getInt("id"), result.getString("name"), result.getString("type")});
}
} catch (SQLException ex) {
Logger.getLogger(Book.class.getName()).log(Level.SEVERE, null, ex);
}
}
private void btnUpdateActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
int row = jTable1.getSelectedRow();
String id = jTable1.getValueAt(row, 0).toString();
try {
// TODO add your handling code here:
st.executeUpdate("Update Book set name ='" + txtName.getText() + "',type='" + txtType.getText() + "' where id =" + id);
displayTable();
} catch (SQLException ex) {
Logger.getLogger(Book.class.getName()).log(Level.SEVERE, null, ex);
}
}
private void btnDeleteActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
int row = jTable1.getSelectedRow();
String id = jTable1.getValueAt(row, 0).toString();
try {
// TODO add your handling code here:
st.executeUpdate("Delete from book where id =" + id);
displayTable();
} catch (SQLException ex) {
Logger.getLogger(Book.class.getName()).log(Level.SEVERE, null, ex);
}
}
You get this error, because you don't select any row, so to avoid this problem you have to use :
if(jTable1.getSelectedRow() != -1){
int row = jTable1.getSelectedRow();
String id = jTable1.getValueAt(row, 0).toString();
//rest of your code here
}else{
//show an error for example, no row is selected
}
Note
Instead of :
st.executeUpdate("Update Book set name ='" + txtName.getText() + "',type='" + txtType.getText() + "' where id =" + id);
You have to use PreparedStatement to avoid any syntax error or SQL Injection
For example :
String query = "Update Book set name = ?, type=? where id =?";
try (PreparedStatement update = connection.prepareStatement(query)) {
update.setString(1, txtName.getText());
update.setString(2, txtType.getText());
update.setInt(3, id);
update.executeUpdate();
}
Another thing, your id is an int so you can't set a String to your query like you do you have to set an int :
String id = jTable1.getValueAt(row, 0).toString();
Instead you have to use :
int id = Integer.parseInt(jTable1.getValueAt(row, 0).toString());
I want to connect a JTable to a ResultSet from a MySQL database so I can view the data.
I am looking for some links or code snippets describing this task. I'm using the Netbeans IDE..
Below is a class which will accomplish the very basics of what you want to do when reading data from a MySQL database into a JTable in Java.
import java.awt.*;
import java.sql.*;
import java.util.*;
import javax.swing.*;
import javax.swing.table.*;
public class TableFromMySqlDatabase extends JFrame
{
public TableFromMySqlDatabase()
{
ArrayList columnNames = new ArrayList();
ArrayList data = new ArrayList();
// Connect to an MySQL Database, run query, get result set
String url = "jdbc:mysql://localhost:3306/yourdb";
String userid = "root";
String password = "sesame";
String sql = "SELECT * FROM animals";
// Java SE 7 has try-with-resources
// This will ensure that the sql objects are closed when the program
// is finished with them
try (Connection connection = DriverManager.getConnection( url, userid, password );
Statement stmt = connection.createStatement();
ResultSet rs = stmt.executeQuery( sql ))
{
ResultSetMetaData md = rs.getMetaData();
int columns = md.getColumnCount();
// Get column names
for (int i = 1; i <= columns; i++)
{
columnNames.add( md.getColumnName(i) );
}
// Get row data
while (rs.next())
{
ArrayList row = new ArrayList(columns);
for (int i = 1; i <= columns; i++)
{
row.add( rs.getObject(i) );
}
data.add( row );
}
}
catch (SQLException e)
{
System.out.println( e.getMessage() );
}
// Create Vectors and copy over elements from ArrayLists to them
// Vector is deprecated but I am using them in this example to keep
// things simple - the best practice would be to create a custom defined
// class which inherits from the AbstractTableModel class
Vector columnNamesVector = new Vector();
Vector dataVector = new Vector();
for (int i = 0; i < data.size(); i++)
{
ArrayList subArray = (ArrayList)data.get(i);
Vector subVector = new Vector();
for (int j = 0; j < subArray.size(); j++)
{
subVector.add(subArray.get(j));
}
dataVector.add(subVector);
}
for (int i = 0; i < columnNames.size(); i++ )
columnNamesVector.add(columnNames.get(i));
// Create table with database data
JTable table = new JTable(dataVector, columnNamesVector)
{
public Class getColumnClass(int column)
{
for (int row = 0; row < getRowCount(); row++)
{
Object o = getValueAt(row, column);
if (o != null)
{
return o.getClass();
}
}
return Object.class;
}
};
JScrollPane scrollPane = new JScrollPane( table );
getContentPane().add( scrollPane );
JPanel buttonPanel = new JPanel();
getContentPane().add( buttonPanel, BorderLayout.SOUTH );
}
public static void main(String[] args)
{
TableFromMySqlDatabase frame = new TableFromMySqlDatabase();
frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
frame.pack();
frame.setVisible(true);
}
}
In the NetBeans IDE which you are using - you will need to add the MySQL JDBC Driver in Project Properties as I display here:
Otherwise the code will throw an SQLException stating that the driver cannot be found.
Now in my example, yourdb is the name of the database and animals is the name of the table that I am performing a query against.
Here is what will be output:
Parting note:
You stated that you were a novice and needed some help understanding some of the basic classes and concepts of Java. I will list a few here, but remember you can always browse the docs on Oracle's site.
ArrayList
Vector
Try-with-resources statement
this is the easy way to do that you just need to download the jar file "rs2xml.jar" add it to your project
and do that :
1- creat a connection
2- statment and resultset
3- creat a jtable
4- give the result set to DbUtils.resultSetToTableModel(rs)
as define in this methode you well get your jtable so easy.
public void afficherAll(String tableName){
String sql="select * from "+tableName;
try {
stmt=con.createStatement();
rs=stmt.executeQuery(sql);
tbContTable.setModel(DbUtils.resultSetToTableModel(rs));
} catch (SQLException e) {
// TODO Auto-generated catch block
JOptionPane.showMessageDialog(null, e);
}
}
If you need to work a lot with database in your code and you know the structure of your table, I suggest you do it as follow:
First of all you can define a class which will help you to make objects capable of keeping your table rows data. For example in my project I created a class named Document.java to keep data of a single document from my database and I made an array list of these objects to keep data of my table which is gain by a query.
package financialdocuments;
import java.lang.*;
import java.util.HashMap;
/**
*
* #author Administrator
*/
public class Document {
private int document_number;
private boolean document_type;
private boolean document_status;
private StringBuilder document_date;
private StringBuilder document_statement;
private int document_code_number;
private int document_employee_number;
private int document_client_number;
private String document_employee_name;
private String document_client_name;
private long document_amount;
private long document_payment_amount;
HashMap<Integer,Activity> document_activity_hashmap;
public Document(int dn,boolean dt,boolean ds,String dd,String dst,int dcon,int den,int dcln,long da,String dena,String dcna){
document_date = new StringBuilder(dd);
document_date.setLength(10);
document_date.setCharAt(4, '.');
document_date.setCharAt(7, '.');
document_statement = new StringBuilder(dst);
document_statement.setLength(50);
document_number = dn;
document_type = dt;
document_status = ds;
document_code_number = dcon;
document_employee_number = den;
document_client_number = dcln;
document_amount = da;
document_employee_name = dena;
document_client_name = dcna;
document_payment_amount = 0;
document_activity_hashmap = new HashMap<>();
}
public Document(int dn,boolean dt,boolean ds, long dpa){
document_number = dn;
document_type = dt;
document_status = ds;
document_payment_amount = dpa;
document_activity_hashmap = new HashMap<>();
}
// Print document information
public void printDocumentInformation (){
System.out.println("Document Number:" + document_number);
System.out.println("Document Date:" + document_date);
System.out.println("Document Type:" + document_type);
System.out.println("Document Status:" + document_status);
System.out.println("Document Statement:" + document_statement);
System.out.println("Document Code Number:" + document_code_number);
System.out.println("Document Client Number:" + document_client_number);
System.out.println("Document Employee Number:" + document_employee_number);
System.out.println("Document Amount:" + document_amount);
System.out.println("Document Payment Amount:" + document_payment_amount);
System.out.println("Document Employee Name:" + document_employee_name);
System.out.println("Document Client Name:" + document_client_name);
}
}
Second of all, you can define a class to handle your database needs. For example I defined a class named DataBase.java which handles my connections to the database and my needed queries. And I instantiated an objected of it in my main class.
package financialdocuments;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* #author Administrator
*/
public class DataBase {
/**
*
* Defining parameters and strings that are going to be used
*
*/
//Connection connect;
// Tables which their datas are extracted at the beginning
HashMap<Integer,String> code_table;
HashMap<Integer,String> activity_table;
HashMap<Integer,String> client_table;
HashMap<Integer,String> employee_table;
// Resultset Returned by queries
private ResultSet result;
// Strings needed to set connection
String url = "jdbc:mysql://localhost:3306/financial_documents?useUnicode=yes&characterEncoding=UTF-8";
String dbName = "financial_documents";
String driver = "com.mysql.jdbc.Driver";
String userName = "root";
String password = "";
public DataBase(){
code_table = new HashMap<>();
activity_table = new HashMap<>();
client_table = new HashMap<>();
employee_table = new HashMap<>();
Initialize();
}
/**
* Set variables and objects for this class.
*/
private void Initialize(){
System.out.println("Loading driver...");
try {
Class.forName(driver);
System.out.println("Driver loaded!");
} catch (ClassNotFoundException e) {
throw new IllegalStateException("Cannot find the driver in the classpath!", e);
}
System.out.println("Connecting database...");
try (Connection connect = DriverManager.getConnection(url,userName,password)) {
System.out.println("Database connected!");
//Get tables' information
selectCodeTableQueryArray(connect);
// System.out.println("HshMap Print:");
// printCodeTableQueryArray();
selectActivityTableQueryArray(connect);
// System.out.println("HshMap Print:");
// printActivityTableQueryArray();
selectClientTableQueryArray(connect);
// System.out.println("HshMap Print:");
// printClientTableQueryArray();
selectEmployeeTableQueryArray(connect);
// System.out.println("HshMap Print:");
// printEmployeeTableQueryArray();
connect.close();
}catch (SQLException e) {
throw new IllegalStateException("Cannot connect the database!", e);
}
}
/**
* Write Queries
* #param s
* #return
*/
public boolean insertQuery(String s){
boolean ret = false;
System.out.println("Loading driver...");
try {
Class.forName(driver);
System.out.println("Driver loaded!");
} catch (ClassNotFoundException e) {
throw new IllegalStateException("Cannot find the driver in the classpath!", e);
}
System.out.println("Connecting database...");
try (Connection connect = DriverManager.getConnection(url,userName,password)) {
System.out.println("Database connected!");
//Set tables' information
try {
Statement st = connect.createStatement();
int val = st.executeUpdate(s);
if(val==1){
System.out.print("Successfully inserted value");
ret = true;
}
else{
System.out.print("Unsuccessful insertion");
ret = false;
}
st.close();
} catch (SQLException ex) {
Logger.getLogger(DataBase.class.getName()).log(Level.SEVERE, null, ex);
}
connect.close();
}catch (SQLException e) {
throw new IllegalStateException("Cannot connect the database!", e);
}
return ret;
}
/**
* Query needed to get code table's data
* #param c
* #return
*/
private void selectCodeTableQueryArray(Connection c) {
try {
Statement st = c.createStatement();
ResultSet res = st.executeQuery("SELECT * FROM code;");
while (res.next()) {
int id = res.getInt("code_number");
String msg = res.getString("code_statement");
code_table.put(id, msg);
}
st.close();
} catch (SQLException ex) {
Logger.getLogger(DataBase.class.getName()).log(Level.SEVERE, null, ex);
}
}
private void printCodeTableQueryArray() {
for (HashMap.Entry<Integer ,String> entry : code_table.entrySet()){
System.out.println("Key : " + entry.getKey() + " Value : " + entry.getValue());
}
}
/**
* Query needed to get activity table's data
* #param c
* #return
*/
private void selectActivityTableQueryArray(Connection c) {
try {
Statement st = c.createStatement();
ResultSet res = st.executeQuery("SELECT * FROM activity;");
while (res.next()) {
int id = res.getInt("activity_number");
String msg = res.getString("activity_statement");
activity_table.put(id, msg);
}
st.close();
} catch (SQLException ex) {
Logger.getLogger(DataBase.class.getName()).log(Level.SEVERE, null, ex);
}
}
private void printActivityTableQueryArray() {
for (HashMap.Entry<Integer ,String> entry : activity_table.entrySet()){
System.out.println("Key : " + entry.getKey() + " Value : " + entry.getValue());
}
}
/**
* Query needed to get client table's data
* #param c
* #return
*/
private void selectClientTableQueryArray(Connection c) {
try {
Statement st = c.createStatement();
ResultSet res = st.executeQuery("SELECT * FROM client;");
while (res.next()) {
int id = res.getInt("client_number");
String msg = res.getString("client_full_name");
client_table.put(id, msg);
}
st.close();
} catch (SQLException ex) {
Logger.getLogger(DataBase.class.getName()).log(Level.SEVERE, null, ex);
}
}
private void printClientTableQueryArray() {
for (HashMap.Entry<Integer ,String> entry : client_table.entrySet()){
System.out.println("Key : " + entry.getKey() + " Value : " + entry.getValue());
}
}
/**
* Query needed to get activity table's data
* #param c
* #return
*/
private void selectEmployeeTableQueryArray(Connection c) {
try {
Statement st = c.createStatement();
ResultSet res = st.executeQuery("SELECT * FROM employee;");
while (res.next()) {
int id = res.getInt("employee_number");
String msg = res.getString("employee_full_name");
employee_table.put(id, msg);
}
st.close();
} catch (SQLException ex) {
Logger.getLogger(DataBase.class.getName()).log(Level.SEVERE, null, ex);
}
}
private void printEmployeeTableQueryArray() {
for (HashMap.Entry<Integer ,String> entry : employee_table.entrySet()){
System.out.println("Key : " + entry.getKey() + " Value : " + entry.getValue());
}
}
}
I hope this could be a little help.
I've been trying to save values into a database called "CLIENT".
The database is created via this code:
package Database;
//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:/WAKILI/WAKILIdb";
// 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), " +
" CARD 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
The class that I'm trying to have save into the database is:
package Database;
//STEP 1. Import required packages
import java.sql.*;
public class JDBCExampleInsertRecords {
public final String values;
public final String table;
public JDBCExampleInsertRecords (String values, String table)
{
this.values = values;
this.table = table;
}
// JDBC driver name and database URL
private static String JDBC_DRIVER = "org.h2.Driver";
private static String DB_URL = "jdbc:h2:file:C:/WAKILI/WAKILIdb";
// Database credentials
private static String USER = "sa";
private static String PASS = "";
public static void main () {
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("Inserting records into the table...");
stmt = conn.createStatement();
String sql = "INSERT INTO CLIENT " + "VALUES ((values))";
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
/**
* #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;
}
} //end
The code that gets the values is in a Class called "AddNewClient" and is as follows:
public String getValues () {
String fullNames = fullNamesJTextField.getText();
String iDNumber = identificationNumberJTextField.getText();
String pINNumber = pINNumberJTextField.getText();
String passportNumber = passportNumberJTextField.getText();
String postOfficeBoxNumber = postOfficeBoxNumberJTextField.getText();
String postalCode = postalCodeJTextField.getText();
String telephoneNumberLandline = telephoneNumberLandlineJTextField.getText();
String telephoneNumberMobile = telephoneNumberMobileJTextField.getText();
List<String> client = new ArrayList<String>();
client.add(fullNames);
client.add(iDNumber);
client.add(pINNumber);
client.add(passportNumber);
client.add(postOfficeBoxNumber);
client.add(postalCode);
client.add(telephoneNumberLandline);
client.add(telephoneNumberMobile);
StringBuilder builder = new StringBuilder();
String listStringClient = "";
for (String s : client)
{
listStringClient += "NULL" + "'" + s + "'" + ",";
}
return listStringClient;
}
I get an error message:
run:
Connecting to a selected database...
Connected database successfully...
Inserting records into the table...
org.h2.jdbc.JdbcSQLException: Column count does not match; SQL statement:
I've been at this for the past two days to no success whatsoever. I will be very, very very greatful to anyone who would come to my rescue. Thank you.
This is where one problem is:
String sql = "INSERT INTO CLIENT " + "VALUES ((values))";
stmt.executeUpdate(sql);
Values should be the getValues() method, instead of just a string, so
String sql = "INSERT INTO CLIENT VALUES (" + getValues() + ")";
Additionally, since you do not specify which columns, it is assumed that all columns are being entered in the values. If CARD does not have a default value in your SQL database, and if it cannot be NULL, you're going to have a problem.
Finally, this is a little strange:
for (String s : client)
{
listStringClient += "NULL" + "'" + s + "'" + ",";
}
You'll want the values, not 'NULL', so it should be
for (String s : client)
{
listStringClient += "'" + s + "'" + ",";
}
And finally, the way you're doing it, you're going to have an extra comma at the end (ex: 'value1','value2','value3',)
Clip the final comma:
return listStringClient.substring(0, listStringClient.size() - 1);
Granted, there's a better way to do the for loop where you do not have that extra comma.
End the end, the sql String should look like this:
"INSERT INTO CLIENT VALUES('value1','value2','value3','value4','value5','value6')"
Do a System.out.println(sql) and see what the String statement is that you're trying to execute. You'll see the error then.
Here's a better way to build your values string without the comma issue:
Iterator<String> iter = client.iterator();
StringBuilder sb = new StringBuilder();
while (iter.hasNext()) {
sb.append("'").append(iter.next()).append("'");
if (iter.hasNext())
sb.append(",");
}
return sb.toString();
You forget to mention the value for CARD column. If you dont want to set any value there, just pass ' '.
Your for loop should be like this
for (String s : client)
{
listStringClient += "NULL" + "'" + s + "'" + ",";//GIVES YOU ERROR BECAUSE AT THE END OF
} // FOR LOOP IT HAS , IN THE END OF STRING.
listStringClient+="' '";//This is for CARD COLUMN.
You do not pass any value in your statement. Following code is static, it does not have parameters:
INSERT INTO CLIENT " + "VALUES ((values))
It is nonsense SQL command: INSERT INTO CLIENT VALUES ((values)). You wanted express
String sql = "INSERT INTO CLIENT VALUES " + getValues()";
I prefer to use PreparedStatement, as it is safe and it will escape dangerous characters:
String sql = "INSERT INTO PRODUCT VALUES(?,?,?,?,?,?,?,?,?,?)";
PreparedStatement prest = con.prepareStatement(sql);
prest.setString(1, "asdf");
prest.setInt(2, 2009);
// etc
int count = prest.executeUpdate();
I think instead of :
String sql = "INSERT INTO CLIENT " + "VALUES ((values))";
You want something like :
String sql = "INSERT INTO CLIENT " + "VALUES ("+getValues()+")";
Also the implementation of getValues is kind of strange :
for (String s : client)
{
listStringClient += "NULL" + "'" + s + "'" + ",";
}
Probably it could be :
for (String s : client)
{
listStringClient += "'" + s + "',"
}
listStringClient += "NULL";
I can't thank you all enough for the amazing answers. I put the various ideas and came up with this solution to my problem.
My working answer to my Question above takes ideas from Leos Literak, abmitchell, Vimal Bera and Grisha's answers.
The database is created via this code:
package Database;
//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:/WAKILI/WAKILIdb";
// 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
The class that saves into the database is:
package Database;
//STEP 1. Import required packages
import java.sql.*;
public class JDBCExampleInsertRecords {
public static String values;
public final String table;
public JDBCExampleInsertRecords (String values, String table)
{
this.values = values;
this.table = table;
}
// JDBC driver name and database URL
private static String JDBC_DRIVER = "org.h2.Driver";
private static String DB_URL = "jdbc:h2:file:C:/WAKILI/WAKILIdb";
// Database credentials
private static String USER = "sa";
private static String PASS = "";
public static void main () {
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("Inserting records into the table...");
stmt = conn.createStatement();
String sql = "INSERT INTO CLIENT VALUES (NULL, " + (values) + ")";
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
/**
* #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;
}
} //end
The code that gets the values is in a Class called "AddNewClient" and is as follows:
public String getValues () {
String fullNames = fullNamesJTextField.getText();
String iDNumber = identificationNumberJTextField.getText();
String pINNumber = pINNumberJTextField.getText();
String passportNumber = passportNumberJTextField.getText();
String postOfficeBoxNumber = postOfficeBoxNumberJTextField.getText();
String postalCode = postalCodeJTextField.getText();
String telephoneNumberLandline = telephoneNumberLandlineJTextField.getText();
String telephoneNumberMobile = telephoneNumberMobileJTextField.getText();
List<String> client = new ArrayList<String>();
client.add(fullNames);
client.add(iDNumber);
client.add(pINNumber);
client.add(passportNumber);
client.add(postOfficeBoxNumber);
client.add(postalCode);
client.add(telephoneNumberLandline);
client.add(telephoneNumberMobile);
Iterator<String> iter = client.iterator();
StringBuilder sb = new StringBuilder();
while (iter.hasNext()) {
sb.append("'").append(iter.next()).append("'");
if (iter.hasNext())
sb.append(",");
}
return sb.toString();
}
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