java.sql.sqlException:no such column: employID - java

Here is my code I am getting the following error"java.sql.sqlException:no such column: employID" and I have rechecked my db table column name is correct employID nothing wrong with that but still getting the same error please help I am trying to load the table data based on the first column into a textboxes using netbeans IDE and sqlite database.
private void tableEmployeeMouseClicked(java.awt.event.MouseEvent evt) {
try{
int row=tableEmployee.getSelectedRow();
String tableClick=(tableEmployee.getModel().getValueAt(row, 0).toString());
String sql="SELECT * FROM employeeInfo WHERE employID=' "+tableClick+" ' ";
pst=conn.prepareStatement(sql);
rs=pst.executeQuery();
if(rs.next()){
String add1=rs.getString("employID");
empid.setText(add1);
String bdd=rs.getString("name");
name.setText(bdd);
String cdd=rs.getString("surname");
surname.setText(cdd);
String ddd=rs.getString("age");
age.setText(ddd);
}
}
catch(Exception e){
JOptionPane.showMessageDialog(null,e);
}
n.b. the employID column in my database is set
to INTEGER can that or my query inside my code have any connection with the error type..
Thanks.
EDIT: The DDL sentence
CREATE TABLE "employeeInfo" (
"employID " INTEGER PRIMARY KEY NOT NULL ,
"name" CHAR, "surname" CHAR,
"age" INTEGER, "username" VARCHAR, "password" VARCHAR)

From the error it is clear that the resultset does not have the column named 'employID'. To troubleshoot this issue you can do either of these:
1. Inspect the resultset metadata and look at the column names that you are getting.
2. Or use column position in resultset.getString() methods to get the values and verify if you are getting employID values.

Related

error while inserting data inside mysql table

String pass=new String(pf1.getPassword());
try {
Connection myConn=DriverManager.getConnection("jdbc:mysql://localhost:3306/javaproject","root","noor1032");
PreparedStatement myStat=myConn.prepareStatement("insert into user_info (username,password,email_id)"+"values(?,?,?)");
myStat.setString(1, tf1.getText());
myStat.setString(2, pass);
myStat.setString(3, tf2.getText());
myStat.execute();
myConn.close();
}
catch(Exception f)
{
System.err.println("Got an exception!");
System.err.println(f.getMessage());
}
I want to insert data entered by user in a JFrame to my sql database. tf1 and tf2 are textfields for username and email_id, respectively. When I execute this statement an exception occurs saying that
Field 'id' does not have a default value
id is a column in my database denoting numbers like 1,2,3 and so on. Please help me.
You have to set the ID as Auto Increment in mysql .It will work
Although you haven't shared your table's structure, I guess that id is a PRIMARY KEY but you missed AUTO_INCREMENT configuration. In your database, run the following statement
ALTER TABLE user_info MODIFY COLUMN id INT auto_increment

Java JDBC adding automatic value to database

I'm working with Java JDBC with Apache Derby data base.
I have a table called `company`` with the values :
id, comp_name, password, email.
This method should create a new row of company with name, password, and email received from the user but the ID should be given automatically from the database and increment itself each time a new company is added to the database.
I just can't figure out how to make this work, I obviously get a error
"column 'ID' cannot accept a NULL value."
because the update occours before the ID is setted.
Code:
public void createCompany(Company company) {
Connection con = null;
try {
con = ConnectionPool.getInstance().getConnection();
String sql = "INSERT INTO company (comp_name, password, email) VALUES (?,?,?)";
PreparedStatement pstmt = con.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
pstmt.setString(1, company.getCompName());
pstmt.setString(2, company.getPassword());
pstmt.setString(3, company.getEmail());
pstmt.executeUpdate();
ResultSet rs = pstmt.getGeneratedKeys();
rs.next();
company.setId(rs.getLong(1));
pstmt.getConnection().commit();
} catch (SQLException e) {
e.printStackTrace();
} finally {
ConnectionPool.getInstance().returnCon(con);
}
During creation of that table you have to write following DDL
CREATE TABLE MAPS
(
comp_id INTEGER NOT NULL GENERATED ALWAYS AS IDENTITY (START WITH 1, INCREMENT BY 1),
comp_name VARCHAR(24) NOT NULL,
password VARCHAR(26)
)
Ref : https://db.apache.org/derby/docs/10.0/manuals/develop/develop132.html
You're doing almost everything right, you just need to let the database assign an unique ID to each inserted row:
CREATE TABLE my_table (
id INTEGER NOT NULL GENERATED ALWAYS AS IDENTITY (START WITH 1, INCREMENT BY 1),
...
);
A problem could be that you made a mistake by creating your table.
You could create your table like this:
CREATE TABLE company
(
ID INTEGER NOT NULL GENERATED ALWAYS AS IDENTITY (START WITH 1, INCREMENT BY 1),
comp_name VARCHAR(50),
email VARCHAR(50),
password VARCHAR (50)
)
IF you want other values to be not NULL you could add NOT NULL to their lines:
password VARCHAR (50) NOT NULL
Delte your old table and execute the the SQl above on your DB. After that you can use your code without changes.

Java derby sql integer query

Please take a look at my code snippet below. What I am trying to achieve is querying the database for any results equal to the user input. It is querying SDS_NUMBER column which is an integer column.
When I execute the query it returns the following exception:
java.sql.SQLSyntaxErrorException: Comparisons between 'INTEGER' and
'CHAR (UCS_BASIC)' are not supported. Types must be comparable.
String types must also have matching collation....etc.
I understand that it is saying I am trying to compare an integer to char but I have tried to cast from examples I found on the net but no luck. Also I tried parseInt and using that value in the search but I still can't get it to work. Please advise what I am doing wrong and excuse my newbies to all of this.
} else if (tmp == "sdsNumber") {
try {
Integer sdsNum = Integer.parseInt(val);
String sql = "SELECT SDS_NUMBER, PRODUCT_NAME, PROPER_SHIPPING_NAME FROM APP.MASTER WHERE SDS_NUMBER = '"+sdsNum+"'";
pst = conn.prepareStatement(sql);
pst.executeQuery();
jTable1.setModel(DbUtils.resultSetToTableModel(rs));
} catch (Exception e) {
e.printStackTrace(System.out);
JOptionPane.showMessageDialog(null, e);
}
Master table creation:
CREATE TABLE MASTER
(
id integer NOT NULL GENERATED ALWAYS AS (START WITH 1, INCREMENT BY 1)
, SDS_NUMBER integer UNIQUE
, PRODUCT_NAME varchar(100)
, PRODUCT_DESCRIPTION varchar(500)
, SDS_FILE_PATH varchar(50)
, USE_STATUS BOOLEAN
, DATA_UPDATED date
, PROPER_SHIPPING_NAME varchar(100)
, SIGNAL_WORD varchar(20)
, CONSTRAINT MASTER_PRIMARY_KEY PRIMARY KEY (id)
);
it seems you're wrapping an integer in quotes
SDS_NUMBER = '"+sdsNum+"'"
probably what you want is
SDS_NUMBER = ?
and then set the number with your PreparedStatement instead of concatenating strings
see http://docs.oracle.com/javase/tutorial/jdbc/basics/prepared.html
and
http://docs.oracle.com/javase/7/docs/api/java/sql/PreparedStatement.html#setInt%28int,%20int%29
Remove the single quote "'"+sdsNum+"'" to be a number
Her ara Example by using preparedStatement
String sql = "SELECT SDS_NUMBER, PRODUCT_NAME, PROPER_SHIPPING_NAME FROM APP.MASTER WHERE SDS_NUMBER = ?";
pst = conn.prepareStatement(sql);
pst.setInt(1, sdsNum);
ResultSet rs = pst.executeQuery(sql);
while (rs.next()) {
int SDS_NUMBER = rs.getInt("SDS_NUMBER");
String PRODUCT_NAME= rs.getString("PRODUCT_NAME");
....
}
} else if ("sdsNumber".equals(tmp)) {
after I changed the first line to this everything works. I dont fully understand what difference that made and if someone could shine some light on it, I would appreciate it as I am slowly learning this.

Getting exception when trying to get the id of the new inserted row

I am trying to get the primary key of the newly inserted record(which is an identity field)
The code snippet is as below
jdbcConnection=new JdbcConnection();
connection=jdbcConnection.getJdbcConnection();
psmt=connection.prepareStatement("{call spCopyRecord(?)}",Statement.RETURN_GENERATED_KEYS);
psmt.setInt(1, primarykey);
int status=psmt.executeUpdate();
ResultSet generatedKeys=psmt.getGeneratedKeys();
if(generatedKeys != null &&generatedKeys.next()){
newKey=generatedKeys.getInt(1);
}
When I try to execute I am getting the exception:
com.microsoft.sqlserver.jdbc.SQLServerException: A result set was generated for update.
which points to executeUpdate statement.
I am using sqljdbc4 jar and SQL version is SQL server 2008.
Please help to fix this issue.Thanks in advance.
You are using:
int status=psmt.executeUpdate();
Is'nt this actually a normal Select query?
Use execute() Or executeQuery()
Pass primary key column name as parameter to method PrepareStatement
prepareStatement(String sql, String[] columnNames) ;
Use above Syntax to get preparestatement which give generated key
jdbcConnection=new JdbcConnection();
connection=jdbcConnection.getJdbcConnection();
psmt=connection.prepareStatement("INSERT QUERY",String[] UR_PRIMARY_KEY_COLUMN_NMAE);
psmt.setInt(1, "params");
int status=psmt.executeUpdate();
ResultSet generatedKeys=psmt.getGeneratedKeys();
while(generatedKeys.next())
{
String id = rs.getString(1);
}

JTable Oracle Timestamp column not displayed

I have created a 'Jtable' named Department_Table and now using SQL query i am trying to populate my Database table contents to my Jtable.
I have done it successfully but the timestamp column from my Database table is not been correctly displayed.
Can you please help me to find whats wrong with this program.
Code:
public void UpdateTable()
{
try
{
Connection conn=Address.getOracleConnection();
String sql="Select * from department";
/*
Using to_char my statement looks like this and it works
String sql="Select department_id,name,to_char(created_on,'dd/MM/yyyy HH24:MI:SS') from department";
*/
PreparedStatement pst=conn.prepareStatement(sql);
ResultSet res=pst.executeQuery();
Department_Tabel.setModel(DbUtils.resultSetToTableModel(res));
}
catch(Exception e)
{
Notify.showMessageDialog(null,""+e+"","Error Generating Table",Notify.ERROR_MESSAGE);
}
}
Output:
departmentid name createdon
1 name1 oracle.sql.TIMESTAMP#19eda2c
2 name2 oracle.sql.TIMESTAMP#59a34
This link should help you understand the mapping and do the formatting in order to display the contents properly.
http://docs.oracle.com/javase/1.5.0/docs/guide/jdbc/getstart/mapping.html

Categories

Resources