How to refresh MS Access database in Java - java

I'm wondering how to refresh database after inserting a new row without reopening whole application. I want to be able to see new data in next steps of my application. I can't find any solution, so i would be happy if you post the example. Of course if it is possible.
Here is my connection method
try{
String driver = "sun.jdbc.odbc.JdbcOdbcDriver";
Class.forName(driver);
String db = "jdbc:odbc:FlowValves";
con = DriverManager.getConnection(db);
st = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_UPDATABLE);
}catch(Exception ex){
ex.printStackTrace();
}
Here is one of my inserting methods.
String sql = "select * from Typy";
try{
ResultSet result;
result = st.executeQuery(sql);
result.moveToInsertRow();
String stringNazwa = (String)nazwaZaworuField.getText();
result.updateString("Typ", stringNazwa);
String stringDN = (String)dnZaworuField.getText();
result.updateString("DN", stringDN);
String stringPN = (String)pnZaworuField.getText();
result.updateString("PN", stringPN);
String stringIndeks = (String)indeksField.getText();
result.updateString("Indeks", stringIndeks);
result.insertRow();
result.close();
JOptionPane.showMessageDialog(null, "Wprowadzono dane", "Komunikat", JOptionPane.INFORMATION_MESSAGE);
}catch(Exception ex){
ex.printStackTrace();
}

Your code for inserting looks correct (although I would use an insert statement instead of using moveToInsertRow() )
You should be able to requery the database and put the new data on the screen:
String sql = "select * from Typy";
ResultSet result;
result = st.executeQuery(sql);
while( result.next() ){
sting indeks = result.getString( "indeks" );
// etc.
// do something with the new data
}

Related

JAVA GUI - GET and SHOW DATA FROM MYSQL

I am working on a GUI app with MySQL access. When user enters some data in JTextField 'VendorID', I want it to be searched in the database, find the proper line with information and show all the columns in other JtextFields seperately. Actually I wanted this data to be showed in JLabel but unsuccessful, so trying now with JtextFields. Appreciate any help from you.
public void findVendor() {
String vatEntered = vendorID.getText();
try
{
String myDriver = "com.mysql.jdbc.Driver";
String myUrl = "jdbc:mysql://localhost:3306/masterdata_db?autoReconnect=true&useSSL=false";
Class.forName(myDriver);
Connection conn = DriverManager.getConnection(myUrl, "root", "");
Statement st = conn.createStatement();
String check = "SELECT * FROM vendorcreation WHERE VAT = 'vatEntered' ";
ResultSet resultSet = st.executeQuery(check);
boolean status = true;
if(resultSet.next()==status){
nameSelected.setText(resultSet.getString(1));
adressSelected.setText(resultSet.getString(2));
countrySelected.setText(resultSet.getString(3));
vatSelected.setText(resultSet.getString(4));
ptermsSelected.setText(resultSet.getString(5));
conn.close();
}
else {
JOptionPane.showMessageDialog(null, "NO DATA FOUND! FIRST YOU MUST CREATE IT", "Inane error",JOptionPane.ERROR_MESSAGE);
dispose();
new CreateVendor().setVisible(true);
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
From what I'm understanding, you're having trouble executing the statement?
You need to set up the statement as following:
String check = "SELECT * FROM vendorcreation WHERE VAT = " +vatEntered ;
But it is better to use a prepared statement instead.
String check = "SELECT * FROM vendorcreation WHERE VAT = ?";
PreparedStatement st = conn.prepareStatement(check);
st.setString(1, vatEntered);
ResultSet resultSet = st.executeQuery();
As for categorizing data, the order seems to depend on the order that the column is in the database. What you can also do is to manually set the result by changing the statement:
String check = "SELECT (column1, column2) FROM vendorcreation WHERE VAT = ?"//etc
where resultSet.getString(1); would be data from column1.

Get data from combobox to database

I'm trying to get category name from combobox and then insert it to my database
This is my code, but I don't know how to write the code to make this work. Any ideas ?
The below code is my add button (trying to make work String value, String query). However, the code is really wrong I think.
String value=jComboBox_Category2.getSelectedItem().toString();
String qquery="INSERT INTO Products ( Cat_products) VALUES ('"+Cat_products.getText()+" ') ";
String query="INSERT INTO Products(Pro_Id ,Pro_Name,Pro_Price,Pro_Quantity,Pro_Supplier_id,Pro_Tax)VALUES ('"+Pro_Id.getText()+" ','"+Pro_Name.getText()+" ','"+Pro_Price.getText()+" ','"+Pro_Quantity.getText()+" ','"+Pro_Supplier_id.getText()+" ','"+Pro_Tax.getText()+" ') ";
executeSQLQuery(query,"Inserted");
Here is the code that my other elements get the data. So where do I have to write the code? And how should it be like?
public ArrayList<Update_del_insert_products> getproList() {
ArrayList<Update_del_insert_products> proList =new ArrayList<Update_del_insert_products> ();
Connection connection =getConnection();
String query ="SELECT * FROM Products";
Statement stt;
ResultSet rss;
try{
stt = connection.createStatement();
rss = stt.executeQuery(query);
Update_del_insert_products update_del_insert_products ;
while(rss.next()) {
update_del_insert_products = new Update_del_insert_products (rss.getString("Pro_Id"),rss.getString("Pro_Name"),rss.getString("Pro_Price"),rss.getString("Pro_Quantity"),rss.getString("Pro_Supplier_id"),rss.getString("Pro_Tax"));
proList.add(update_del_insert_products);
}
}catch (Exception e){
e.printStackTrace();
}
return proList;
}
String qquery="INSERT INTO Products (Cat_products) VALUES (Cat_products.getText()");
Connection connection = (see below)
Statment stmt = connection.createStatement();
stmt.executeUpdate(qquery)
But you can concatenate insert statements if you use the same table
In order to retrieve data from database, first of all have to set the connection properly
Connection connection = DriverManager.getConnection("jdbc:sqlserver://localhost;databaseName=YourDatabseName;integratedSecurity=true;")//without authentication
You should not use * in sql statement.
Make setter and getter methods in Update_del_insert_product class (Auto-generated methods) and use them.
while(rss.next()){
update_del_insert_products product = new Update_del_insert_products();
int i = 1
product.setPro_ID(rss.getString(Pro_ID, i++));
product.setPro_Name(rss.getString(Pro_Name, i++));
...
prolist.add(product);
}

Same input list to two different queries in sql server using java db method

I want to establish single connection with sql server for two different queries having same input.
Is that acheivable?
Here is my code which will establish the connection with database twice for executing queries seperately with same input.
String query1="select ID_Student,Lib_Sec_Book from Library_db1 where ID_Student";
String query2="select ID_Student,Lib_Sec_Book from Library_db2 where ID_Student";
Map<String, String> result1=dba.dbcon(inputListMismatch,query1);
Map<String, String> result2=dba.dbcon(inputListMismatch,query2);
these queries have same student IDs as input,I need to find out which ID having book from two library databases.It may mutually exclusive.
saving resultset of query1 and query2 in result1 and result2 respectively
two results need to be in single Map.
In dba method,
Map<String, String> result=new HashMap<String,String>();
try {
String databaseDriver = "net.sourceforge.jtds.jdbc.Driver";
Class.forName(databaseDriver);
}
catch (Exception e) {
e.printStackTrace();
}
try
{
String url = "jdbc:jtds:sqlserver://server;instance=";
java.sql.Connection con =DriverManager.getConnection(url);
System.out.println("Connection created");
String sqlQuery=query+" "+getIn(list.size());
PreparedStatement preparedStatement = con.prepareStatement(sqlQuery);
for(int i=0; i<list.size(); i++)
preparedStatement.setString(i+1, (String) list.get(i));
ResultSet rs = preparedStatement.executeQuery();
ResultSetMetaData rsMeta=rs.getMetaData();
int colcount=rsMeta.getColumnCount();
result.put(rsMeta.getColumnName(1),rsMeta.getColumnName(2));
while(rs.next())
{
result.put(rs.getString(1),rs.getString(2));
}
rs.close();
preparedStatement.close();
con.close();
}
catch (Exception e1)
{
e1.printStackTrace();
}
return result;
}
getting input list
static String getIn(int numParams) {
StringBuilder builder = new StringBuilder("IN (?");
for(int i=1; i<numParams; i++)
builder.append(",?");
builder.append(")");
return builder.toString();
}
Now I am getting two different resultset, I want to pass two queries in a single instance.
I tried union,It is throwing "Parameter has not been set" error.
and I have also tried 'allowMultiQueries=TRUE" that is not helping.
Can you suggest better way of doing this?
I am not sure what you want,but I try to give you some suggestions.
If you are looking for a solution to improve performance,use two threads to query simultaneously. Use http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ExecutorService.html to control threads.
If you want to merge two queries into one query , try the following code to build sql.
String sqlQuery=query+" "+getIn(list1.size()) +" union "+ getIn(list2.size());
PreparedStatement preparedStatement = con.prepareStatement(sqlQuery);
for(int i=0; i<list1.size(); i++)
preparedStatement.setString(i+1, (String) list.get(i));
for(int i=0; i<list2.size(); i++)
preparedStatement.setString(list1.size()+i+1, (String) list.get(i));
I have tested the following code using DB2 database , and I think it will work well with other dbs. Because jdbc will make sure its API's are suitable for different database .
String urlRemote = "jdbc:db2://fake_ip_address:60004/fake_db_instance_name";//远程方式连接DB2的默认端口为6789
String strJDBCRemote = "com.ibm.db2.jcc.DB2Driver";
String userName = "fake_user";
String password = "fake_password";
Class.forName(strJDBCRemote);
//连接远程时必须要有用户名和密码,否则连接时报错
Connection con = DriverManager.getConnection(urlRemote,userName,password);
String sql = "select id,value from fake_table1 where id=? union select member_number as id,dbindx_number as value from fake_table2";
PreparedStatement pstmt = con.prepareStatement(sql);
pstmt.setString(1,"1");
ResultSet rs = pstmt.executeQuery();
while(rs.next()){
System.out.println(rs.getString(1)+" "+rs.getString(2));
}
con.close();

How to call parameterized stored procedure in jdbc

I need to call a parameterized stored procedure in java jdbc from sql server.
The stored procedure goes like this in sql
create proc patientreg
#id int
as
begin
select [patient_id],[Psurname], [pFirstname], [pMiddlename], [reg_date], [DOB], [Sex], [Phone_num], [Addr],[Email],[dbo].[fncomputeage](DOB) from [dbo].[Patient_registration] where [patient_id] = #id
end
please note dbo.fncompute(DOB) is a function
To call it in JDBC:
try{
String str = "{call patientreg(?)}";
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con = DriverManager.getConnection("jdbcdbc:GeneralHospital");
cstmt = con.prepareCall(str);
cstmt.setInt(1, Integer.parseInt(t.getText()));
cstmt.execute();
int pid = cstmt.getInt(1);
String sname = cstmt.getString(2);
String fname = cstmt.getString(3);
String mname = cstmt.getString(4);
String regdate = cstmt.getString(5);
String dob = cstmt.getString(6);
String sex = cstmt.getString(7);
String phonenum = cstmt.getString(8);
String address = cstmt.getString(9);
String email = cstmt.getString(10);
int age = cstmt.getInt(11);
l1.setText(sname+""+ fname+""+mname);
l3.setText(Integer.toString(pid));
l4.setText(regdate);
l5.setText(dob);
l6.setText(Integer.toString(age));
l7.setText(sex);
l8.setText(phonenum);
l9.setText(address);
l10.setText(email);
cstmt.close();
}
catch(Exception ex)
{
System.out.println("Error occured");
System.out.println("Error:"+ex);
}
After doing it this way it throwing an exception:
Error:java.sql.SQLException: Parameter 1 is not an OUTPUT parameter
there is a couple of problems with your code.
First, Don't use the jdbc odbc driver! It is unstable, and might not work correctly. Use Microsoft's own jdbc driver, or, even better, use jTDS, which is an excellent open source jdbc driver for Sql Server.
Second, the getInt, getString etc methods on CallableStatement is used to retrieve output parameters from the stored procedure. What you have is an ordinary resultset.
CallableStatement cstmt = con.prepareCall("{call patientreg(?)}");
// add input parameter
cstmt.setInt(1, someInteger);
// execute and get resultset.
ResultSet rs = cstmt.executeQuery();
// read resultset
while (rs.next()) {
int pid = rs.getInt(1);
String sname = rs.getString(2);
String fname = rs.getString(3);
// etc.
}
// remember to close statement and connection
try this
ResultSet rs = null;
PreparedStatement cs=null;
Connection conn=getJNDIConnection();
try {
cs=conn.prepareStatement("exec sp_name ?,?");
cs.setString(1, "val1");
cs.setString(2, "val2");
rs = cs.executeQuery();
ArrayList<YourClass> listYourClass = new ArrayList<YourClass>();
while (rs.next()) {
YourClassret= new YourClass();
ret.set1(rs.getString(1));
ret.set2(rs.getString(2));
ret.set3(rs.getString(3));
listaObjectX.add(ret);
}
return listYourClass ;
} catch (SQLException se) {
System.out.println("Error "+ se.getMessage());
se.printStackTrace();
} finally {
try {
rs.close();
cs.close();
con.close();
} catch (SQLException ex) {
//do ex.print
}
}

Java - Getting Data from MySQL database

I've connected to a MySQL database, which contains four fields (the first of which being an ID, the latter ones each containing varchar strings).
I am trying to get the last row of the database and retrieve the contents of the fields so that I can set them to variables (an int and three strings) and use them later.
So far, I have the bare minimum to make the connection, where do I go from here? As you can see I have tried to write a SQL statement to get the last row but it's all gone wrong from there and I don't know how to split it into the separate fields.
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection con = DriverManager.getConnection("jdbc:mysql://localhost/t", "", "");
Statement st = con.createStatement();
String sql = ("SELECT * FROM posts ORDER BY id DESC LIMIT 1;");
st.getResultSet().getRow();
con.close();
Here you go :
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection con = DriverManager.getConnection("jdbc:mysql://localhost/t", "", "");
Statement st = con.createStatement();
String sql = ("SELECT * FROM posts ORDER BY id DESC LIMIT 1;");
ResultSet rs = st.executeQuery(sql);
if(rs.next()) {
int id = rs.getInt("first_column_name");
String str1 = rs.getString("second_column_name");
}
con.close();
In rs.getInt or rs.getString you can pass column_id starting from 1, but i prefer to pass column_name as its more informative as you don't have to look at database table for which index is what column.
UPDATE : rs.next
boolean next()
throws SQLException
Moves the cursor froward one row from its current position. A
ResultSet cursor is initially positioned before the first row; the
first call to the method next makes the first row the current row; the
second call makes the second row the current row, and so on.
When a call to the next method returns false, the cursor is positioned
after the last row. Any invocation of a ResultSet method which
requires a current row will result in a SQLException being thrown. If
the result set type is TYPE_FORWARD_ONLY, it is vendor specified
whether their JDBC driver implementation will return false or throw an
SQLException on a subsequent call to next.
If an input stream is open for the current row, a call to the method
next will implicitly close it. A ResultSet object's warning chain is
cleared when a new row is read.
Returns:
true if the new current row is valid; false if there are no more rows Throws:
SQLException - if a database access error occurs or this method is called on a closed result set
reference
Something like this would do:
public static void main(String[] args) {
Connection con = null;
Statement st = null;
ResultSet rs = null;
String url = "jdbc:mysql://localhost/t";
String user = "";
String password = "";
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection(url, user, password);
st = con.createStatement();
rs = st.executeQuery("SELECT * FROM posts ORDER BY id DESC LIMIT 1;");
if (rs.next()) {//get first result
System.out.println(rs.getString(1));//coloumn 1
}
} catch (SQLException ex) {
Logger lgr = Logger.getLogger(Version.class.getName());
lgr.log(Level.SEVERE, ex.getMessage(), ex);
} finally {
try {
if (rs != null) {
rs.close();
}
if (st != null) {
st.close();
}
if (con != null) {
con.close();
}
} catch (SQLException ex) {
Logger lgr = Logger.getLogger(Version.class.getName());
lgr.log(Level.WARNING, ex.getMessage(), ex);
}
}
}
you can iterate over the results with a while like this:
while(rs.next())
{
System.out.println(rs.getString("Colomn_Name"));//or getString(1) for coloumn 1 etc
}
There are many other great tutorial out there like these to list a few:
http://www.vogella.com/articles/MySQLJava/article.html
http://www.java-samples.com/showtutorial.php?tutorialid=9
As for your use of Class.forName("com.mysql.jdbc.Driver").newInstance(); see JDBC connection- Class.forName vs Class.forName().newInstance? which shows how you can just use Class.forName("com.mysql.jdbc.Driver") as its not necessary to initiate it yourself
References:
http://zetcode.com/databases/mysqljavatutorial/
This should work, I think...
ResultSet results = st.executeQuery(sql);
if(results.next()) { //there is a row
int id = results.getInt(1); //ID if its 1st column
String str1 = results.getString(2);
...
}
Easy Java method to get data from MySQL table:
/*
* CREDIT : WWW.CODENIRVANA.IN
*/
String Data(String query){
String get=null;
try{
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection con = (Connection)DriverManager.getConnection
("jdbc:mysql://localhost:3306/mysql","root","password");
Statement stmt = (Statement) con.createStatement();
ResultSet rs=stmt.executeQuery(query);
if (rs.next())
{
get = rs.getString("");
}
}
catch(Exception e){
JOptionPane.showMessageDialog (this, e.getMessage());
}
return get;
}
Here is what I just did right now:
import java.sql.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import com.sun.javafx.runtime.VersionInfo;
public class ConnectToMySql {
public static ConnectBean dataBean = new ConnectBean();
public static void main(String args[]) {
getData();
}
public static void getData () {
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/mynewpage",
"root", "root");
// here mynewpage is database name, root is username and password
Statement stmt = con.createStatement();
System.out.println("stmt " + stmt);
ResultSet rs = stmt.executeQuery("select * from carsData");
System.out.println("rs " + rs);
int count = 1;
while (rs.next()) {
String vehicleType = rs.getString("VHCL_TYPE");
System.out.println(count +": " + vehicleType);
count++;
}
con.close();
} catch (Exception e) {
Logger lgr = Logger.getLogger(VersionInfo.class.getName());
lgr.log(Level.SEVERE, e.getMessage(), e);
System.out.println(e.getMessage());
}
}
}
The Above code will get you the first column of the table you have.
This is the table which you might need to create in your MySQL database
CREATE TABLE
carsData
(
VHCL_TYPE CHARACTER(10) NOT NULL,
);
First, Download MySQL connector jar file, This is the latest jar file as of today [mysql-connector-java-8.0.21].
Add the Jar file to your workspace [build path].
Then Create a new Connection object from the DriverManager class, so you could use this Connection object to execute queries.
Define the database name, userName, and Password for your connection.
Use the resultSet to get the data based one the column name from your database table.
Sample code is here:
public class JdbcMySQLExample{
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/YOUR_DB_NAME?useSSL=false";
String user = "root";
String password = "root";
String query = "SELECT * from YOUR_TABLE_NAME";
try (Connection con = DriverManager.getConnection(url, user, password);
Statement st = con.createStatement();
ResultSet rs = st.executeQuery(query)) {
if (rs.next()) {
System.out.println(rs.getString(1));
}
} catch (SQLException ex) {
System.out.println(ex);
}
}

Categories

Resources