I am new on working with java(Embedded) databases and derby. I am creating a java application in netbeans ide 8.0. I was able to set up the database and insert data on it. I tried to select rows on one of my db's tables and as expected I saw the rows i inserted. But when i try to select from my code/project, it returns no result. The connection is successfully established as per the logs and no errors encountered. I don't know what to do anymore. :(
Here's my code:
try {
Connection con = DriverManager.getConnection("jdbc:derby:AccountingDB"); /* Note use' / 'and not' \' The url above will be different in your system*/
PreparedStatement stmt = con.prepareStatement("SELECT * from app.companies");
ResultSet rs = stmt.executeQuery();
if(rs.next())
{
companySet.addItem(rs.getString("name"));
//System.out.println("Id : "+rs.getInt(1) +" "+" Fruitname :"+rs.getString(2));
}
else
{
System.out.println("No word matching in database");
}
} catch (SQLException err) {
System.out.println(err.getMessage()+ "No matching word in database");
}
i did this on the customize code of my jComboBox.
thanks. I hope I explained my problem well. :(
Related
I have this error code in the dialog box: java.sql.SQLException: No value specified for parameter 5 when i try to update my JTable/JTextFields into my SQL database.
I have checked similar questions on the site, but non seem to have the solution to my problem. I have checked the database, i have checked my connection code, the update code and can't find where this extra parameter making the problem should be? Please help a new beginner!
So now i understand that the problem is at WHERE id=? as i suspected, but my id only exist as a row count/main key in my SQL DB, so it is going to be different depending on which row you choose/click on, so i can't set a specific value beforehand at the pst.setInt(5, ? ). What to insert instead then - so i dont lose the automatic row count on my clients list in the JTable?
//This method contains all codes for database connection.
private void upDateDB() {
try {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/num klienter", "root", "");
PreparedStatement pst = con.prepareStatement("SELECT * FROM klient");
ResultSet rs =pst.executeQuery();
ResultSetMetaData StData = rs.getMetaData();
q = StData.getColumnCount();
DefaultTableModel RecordTable = (DefaultTableModel)table.getModel();
RecordTable.setRowCount(0);
while(rs.next()){
Vector<String> columnData = new Vector<String>();
for (i = 1; i <= q; i++) {
columnData.add(rs.getString("id"));
columnData.add(rs.getString("Name"));
columnData.add(rs.getString("Birthday"));
columnData.add(rs.getString("Description"));
columnData.add(rs.getString("Other"));
}
RecordTable.addRow(columnData);
}} catch (Exception ex) {
JOptionPane.showMessageDialog(null, ex);
}}
updateButton.addActionListener(new ActionListener() {
public void actionPerformed (ActionEvent arg0) {
try {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost/num klienter", "root", "");
PreparedStatement pst = con.prepareStatement("UPDATE klient SET Name=?,Birthday=?,Description=?,Other=? WHERE id=?");
table.getSelectedRow();
pst.setString(1, nameTxt.getText());
pst.setString(2, dayTxt.getText()+"-" + monthTxt.getText()+"-" + yearTxt.getText());
pst.setString(3, descriptionTxt.getText());
pst.setString(4, otherTxt.getText());
pst.executeUpdate();
JOptionPane.showMessageDialog(null, "Updated in database");
upDateDB();
}catch (Exception ex){
JOptionPane.showMessageDialog(null, ex);
}
Class.forName("com.mysql.cj.jdbc.Driver");
this can just be removed. It hasn't been neccessary for 20 years.
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/num klienter", "root", "");
This is a memory leak; the connection is opened, and will remain open forever; your SQL server won't allow more than a handful of open connections, so pretty soon your MySQL server will be unreachable by any service (including this java code) until you kill the java app which closes the connections. Use try with resources for all resources you create.
PreparedStatement pst = con.prepareStatement("SELECT * FROM klient");
This is also a resource and needs try-with-resources.
ResultSet rs =pst.executeQuery();
You guessed it. Try-with-resources a third time. If you find the code becoming unwieldy, JDBC is very low level and not all that great for 'end user' coding. Use a nice abstraction like JDBI or JOOQ.
columnData.add(rs.getString("Fødselsdag"));
non-ASCII in your column names? That's never going to go well. I strongly suggest you don't do it this way.
q = StData.getColumnCount();
for (i = 1; i <= q; i++) {
This is bizarre. q holds the column count - that's the number of columns in your query. And then you hardcode the 5 column names, so q is always 5. Then, you add all 5 values (id, Navn, Fødselsdag, etc), and then do that 5 times, for a total of 25 runs, and your data repeated 5 times. It is not clear what you are trying to accomplish by asking for the known information (get the column count from the metadata, which you already know).
PreparedStatement pst = con.prepareStatement("UPDATE klient SET Navn=?,Fødselsdag=?,Beskrivelse=?,Andet=? WHERE id=?");
I count 5 ?, but only 4 pst.setString statements. You forgot pst.setInt(5, theValue).
The update code gets all the same caveats about try-with-resources.
pst.setString(2, dayTxt.getText()+"-" + monthTxt.getText()+"-" + yearTxt.getText());
Not how you do date stuff with DBs. There is a pst.setDate, but optimally you should use pst.setObject, passing an instance of java.time.LocalDate. Whether MySQL actually supports that - not sure, you'd have to check.
The solution for my problem was to insert the 5th pst. statement for the id=? like this:
pst.setInt(5,table.getRowCount());
Cheers everyone, beginner here!.
I'm currently working on a Java application to keep track of the inventory in our warehouse. It's all on localhost until it's finished. I've created two tables in MySQL database: one table shows the article code, location and quantity (VOORRAADSYSTEEM); the other table shows article code and description (STAMDATA).
In my GUI, I've got a JTable which loads data from VOORRAADSYSTEEM, and on mouseclickevent (getSelectedRow) shows the data in the corresponding JTextFields (so far so good). The only field not showing is the description field (which should be read from the STAMDATA table).
I've tried creating a method for this specific part of the program. The method runs a query to the second table using a inner join to the first table. Here's the code below.
private void LoadDescription() {
try {
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/ABEL?zeroDateTimeBehavior=convertToNull", "root", "");
String sql = "SELECT DESCRIPTION FROM VOORRAADSYSTEEM JOIN STAMDATA ON ARTICLECODE = ARTICLENUMBER WHERE ARTICLECODE="+jComboBox1.getSelectedItem();
pst = conn.prepareStatement(sql);
rs = pst.executeQuery();
pst.setString(2, sql);
descriptionTxt.setText(rs.getString(sql));
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e);
}
}
At this moment I'm not exactly sure how to approach this problem. I'm also going to try using foreign keys. Any help would be appreciated.
There are better ways to handle what you want to do. For instance you could get all the information you need with one query by joining the table on a common column (ARTICLENUMBER and ARTICLECODE) and then display it.
Right now it looks/sounds like you might be trying to get all the information with two queries.
However, there are some errors with your load description method:
private void LoadDescription() {
try {
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/ABEL?zeroDateTimeBehavior=convertToNull", "root", "");
String sql = "SELECT DESCRIPTION FROM VOORRAADSYSTEEM JOIN STAMDATA ON ARTICLECODE = ARTICLENUMBER WHERE ARTICLECODE="+jComboBox1.getSelectedItem();
ResultSet results = conn.createStatment().executeQuery(sql);
if(results.next()) //make sure something was returned to avoid null pointer exception
descriptionTxt.setText(rs.getString("DESCRIPTION"));
else
JOptionPane.showMessageDialog(null, "no results returned");
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e);
}
}
This should work a little better for you.
I am trying to connect java derby db and insert into a table. Everything goes ok but data is not inserted although there is no error at all. Cn you please let me know whats wrong? i tried to change the code and even created new database n table still same. Code works wihtout error but data is not inserted.
Here is my code
databasetest.java
package databasetest;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
public class DatabaseTest {
public static void main(String[] args) {
try{
Class.forName("org.apache.derby.jdbc.ClientDriver");
System.out.println(" class found " );
}catch(Exception e){
System.out.println("Not found driver class" + e);
};
try{
Connection conn = null;
String pass =null;
conn = DriverManager.getConnection("jdbc:derby://localhost:1527/user","APP",pass);
System.out.println(" Connected to database " );
try{
Statement st;
System.out.println(" inserted");
conn.close();
}catch(Exception e){
System.out.println(" Eror in inserting" + e );
}
}catch(Exception e){
System.out.println("Mistake happnd " + e);
}
}
}
here is run result
run:
class found
Connected to database
inserted
BUILD SUCCESSFUL (total time: 0 seconds)
Please can some one tell me whats going wrong?
Thanks in advance
The problem seems to reside here: Statement st;. You are creating a statement object but you are not associating any queries to it.
Please take a look at this Oracle Tutorial for more information on the matter.
Your code is not actually trying to insert anything.
Statement st;
System.out.println(" inserted");
conn.close();
This doesn't really do anything other than close the connection.
Usually you will want to create a PreparedStatement with a query like
PreparedStatement st = conn.prepareStatement("place your SQL Query here");
st.execute();
alternatively you could look into the API for PreparedStatement.
If you are set on using a regular Statement or your query is simple and does not involve insecure input, you can use
Statement stmt = conn.createStatement();
stmt.execute("Simple SQL Query here");
from the code looks like You have just created the connection with database.
there is no code to insert something into the database.
add the following code to insert some value into your database.
Statement stmt=con.createStatement();
String query="Insert into table_name values (comma separated sequential column value)"; //here comes your insertion query
ResultSet rs=stmt.executeQuery(query);
i have one problem with database in java
my code is ( its only one small part of my project)
public void Read_from_DB(int exhibition_id){
Statement stmt = null;
Connection connect = null;
try {
connect=MYConnection.new_connection();
stmt = connect.createStatement();
QuestionCatalog.get_QuestionCatalog_instance().setShow_quest(new ArrayList<Question>());
String sql = "SELECT * FROM question WHERE Selection=0 AND exhibition_id="+exhibition_id;
//System.out.println(sql);
ResultSet rs = stmt.executeQuery(sql);
System.out.println("!");
System.out.println("->"+rs.getFetchSize());
while(rs.next()){
Question jd=new Question();
System.out.println("!!!");
jd.setQuestion_id(rs.getInt("Question_id"));
jd.setQuestion(rs.getString("Question"));
jd.setQuestion(rs.getString(exhibition_id));
jd.getOption_2().setContent(rs.getString("Content2"));
QuestionCatalog.get_QuestionCatalog_instance().getShow_quest().add(jd);
System.out.println("size"+QuestionCatalog.get_QuestionCatalog_instance().getShow_quest().size());
MYConnection.close_connection(stmt, connect);
}
}catch (Exception e) {
}
}
when i execute this code it dosent work
my database table name is "question"
but when i change the name in this query to "Question" , don't get any error
then i think it doesn't execute my query,my main is
public static void main(String[] args) {
DB_question d=new DB_question();
d.Read_from_DB(1);
}
and "MYConnection.new_connection();" in part on of code return a connection,( i test it in another class it work)
the result in console is :
SELECT * FROM Question WHERE Selection=0 AND exhibition_id=1
!
->0
it haven't show "!!!"that is result of "System.out.println("!!!");"
then i think it doesnt work :|
thanks
p.s the picture of my db
picture
What I understand from your question is improper output on case sensitive names on table names or column names. Am I right?
As far as I know, reserved words like SELECT, FROM, etc. are case in-sensitive in all OS's. And all other user defined object names are case-sensitive, in *ix OS environment. But not in in Windows OS environment.
But all RDBMS configurations should be allowing case-insensitivity for cross platform deployment. This is the reason why your change from question to Question did not throw an error.
And regarding the outcome of your query:
I fear you have tested your query on different databases or servers. They might not have same data and hence always not entering into while( rs.... loop.
Change your code as below and see what the output is:
ResultSet rs = stmt.executeQuery(sql);
System.out.println("!");
System.out.println("->"+rs.getFetchSize());
rs.beforeFirst();
rs.last();
int rowCount = rs.getRow();
System.out.println( "---> rowCount: " + rowCount );
rs.beforeFirst();
while( ...
Also refer to:
DBMS Identifiers and Case Sensitivity - MysQL
I have been able to link postgresql with java. I want the user to input a name in a text box in java and a search is performed and checks if the name exists in the database.
My code so far:
String hostname=this.hostNameText.getText();
try
{
s = connection.createStatement();
String q="SELECT * FROM hostdetails WHERE \"HOSTNAME\" = "+hostname;
rs = s.executeQuery(q);
}catch(Exception e)
{
System.out.println("Problem in searching the database 1");
}
I am getting problem to link to the table hostdetails. Please note that hostdetails contain a field nammed HOSTNAME(in capital letters). When I run the above code, I get "Problem in searching the database 1"is displayed. Kindly please help me:)
Try using parameterized queries to protect against SQL injection. Use as follows:
String hostname=this.hostNameText.getText();
try
{
String q="SELECT * FROM hostdetails WHERE \"HOSTNAME\" = ?"; //notice change here
//and use params like this
PreparedStatement pStmnt = connection.prepareStatement(q);
pStmnt.setString(1, hostname);
rs = pStmnt.executeQuery(q);
}catch(Exception e)
{
//error handling here
}