I am trying to access a database from a different server , but no success so far. The event is, when I choose the object "ALL" in my combobox, the table will load all data from different servers.
The current code, which I only connected to the localhost, works fine. However, when I try to connect another server to load both of their data, I get a syntax error when trying to put 192.168.1.51.sales.items in the String sqlall. Also, I tried modifying the prepareStatement by writing cn.prepareStatement(sqlall) + cn1.prepareSatement("union Select * from 192.168.1.52.sales.items); I have no more idea on how to connect on both servers.
I would like to apologize beforehand if you find my coding a bit messy. Thank you. My code is as follows:
private void combobox_branchItemStateChanged(java.awt.event.ItemEvent evt) {
Object branch = combobox_branch.getSelectedItem();
try
{
// All is selected
if("All".equals(branch))
{
Connection cn = db.itemconnector.getConnection();
String sqlall = " Select * from sales2.items union Select * from sales1.items union Select * from sales.items " ; //I tried accessing multiple databases in my own localhost and worked.
PreparedStatement ps = cn.prepareStatement(sqlall);
ResultSet rs = ps.executeQuery();
DefaultTableModel tm = (DefaultTableModel)itemTable.getModel();
tm.setRowCount(0);
while(rs.next())
{
Object o[] = {rs.getInt("id"), rs.getString("location"), rs.getString("product_name"),rs.getString("product_category"),rs.getString("product_description"),rs.getInt("product_stock"), rs.getFloat("product_price"), rs.getString("product_status")};
tm.addRow(o);
}
}
catch (Exception e)
{
JOptionPane.showMessageDialog(null, e, "Connection Error", JOptionPane.ERROR_MESSAGE);
}
}
And I have a class in a different package and this is its code:
package db;
import java.sql.*;
public class itemconnector {
public static Connection getConnection() throws Exception
{
Class.forName("com.mysql.jdbc.Driver");
Connection cn = (Connection)
DriverManager.getConnection("jdbc:mysql://192.168.1.50:3306/sales","root","");
return cn;
}
It is not possible to query different databases on different servers in a single SQL query.
It is also not possible to get around this by "concatenating" prepared statements. (For a start, that is nonsensical Java!)
You need to open a separate Connection to each separate database server and query the relevant tables on that server. Then combine the information from the separate ResultSet objects in Java code.
The "combining" will be something like iterating the results in each result set and adding them to a Java data structure ...
Related
I have a problem when I enter data from the application to mysql database, it appears in the form of "????" However, when I enter data via "phpmyadmin" the data appears normally
well the problem is when i enter data via application ,
not related with database
any way i tried to change the encode of database and the table and the fields inside the tables
here the insert query in my application
public static void dbConnect() {
try{
Class.forName(DRIVER);
connector = DriverManager.getConnection(DATA_BASE_BATH, "root", "");
insert = connector.prepareStatement("INSERT INTO students VALUES (?,?,?,?)");
}
public static void insert(int id , String name , String special , double gpa){
dbConnect();
try{
insert.setInt(1, id);
insert.setString(2, name);
insert.setString(3,special);
insert.setDouble(4,gpa);
insert.execute();
}
catch(SQLException e){
System.out.println(e.getMessage());
}
}
here the image to understand the problem
-the first row is the data entry from the application
-and the second row is the data entry manually from the phpmyadmin
Your application isn't properly handling the data.
You need to set the charset during the connection to the MySQL server.
Perhaps by running the command SET NAMES 'UTF8'; as part of your connection script.
This answer states that you can even make it part the JDBC connection string in DATA_BASE_BATH when referenced in your getConnection() function call, as does this one.
I try to create a connection between JDBC and MS Access.
I follow the instruction as per this link. I am using IntelliJ Idea. Here I am sharing some snaps to describe my problem.
This is the code that I write down to make a connection with Database Database2. But as you can see there is no error neither any output. Now I am sharing the table structure and content on the table.
2nd picture is
My code is:
import java.sql.*;
public class Connection_sample {
public static void main(String[] args) {
try {
Class.forName("net.ucanaccess.jdbc.UcanaccessDriver");
Connection conn= DriverManager.getConnection("jdbc:ucanaccess://D://tutorial/Database2.accdb");
Statement s = conn.createStatement();
s.executeQuery("select * from Student");
ResultSet rset = s.getResultSet();
while (rset.next()) {
System.out.println(rset.getInt(1)+""+rset.getInt(2));
}
} catch (SQLException | ClassNotFoundException e) {
e.printStackTrace();
}
}
}
Can anyone help me to find the error?
Your problem is the result of using getResultSet() instead of using the result set returned by executeQuery(). You should only use getResultSet() in combination with execute().
A result set should only be obtained once, and it was already returned from executeQuery (which you ignored). When you called getResultSet, you - apparently - got an empty one (which technically violates the contract).
I am trying and failing to send data from my java gui to my MS SQL database, I have dabbled with Java in the past but by no means am I an expert, I have been sourcing help from online and I have managed to connect my database to my application but i seem to be struggling with transferring data from the text fields to the database. (I am also new to stack so please put me straight in my place if I am out of line)
I have a class for my UI and a class for the database connection, the code is from a online resource and it seems straight forward and logical to follow (in my eyes) but I cannot seem to crack what should be a simple problem. The process is get the text from the text field and insert using a statement in to the SQL database, I can send data from within my code easily but I would ideally like it from the text fields.
The code cannot seem to see the "Connection" - error = java.lang.RuntimeException: Uncompilable source code - cannot find symbol
symbol: class Connection
I apologise in advance if this is a very simple mistake but it is driving me insane as it should be a fairly straight forward process. In plain terms it should be able to fill out the four text fields which fill the four columns in my DB when the submit button is pressed. Any help would be greatly appreciated.
this is the code for the action on my button:
private void SubmitBTNActionPerformed(java.awt.event.ActionEvent evt) {
String name = Name.getText();
String number = Number.getText();
String title = Title.getText();
String year = Year.getText();
String query = "insert into students values ('"+Name+"','"+Number+"','"+Title+"','"Year+"')";
System.out.println(query);
try {
Connection c = DatabaseConnection.getConnection();
Statement stmt = c.createStatement();
stmt.executeUpdate(query);
} catch (Exception e) {
e.printStackTrace();
}
}
this is the code in my database class
public class DatabaseConnection {
static private Connection connection;
public static Connection getConnection() throws Exception{
if(connection == null){
//JDBC
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
connection = DriverManager.getConnection("jdbc:sqlserver://localhost:1433;databaseName=*******;user=****;password=******;");
}
return connection;
}
}
Thanks
Code snippet:
On a button click, actionevent will be called
public void actionPerformed(ActionEvent e)
{
Function f = new Function();
Function is a nested class which i have used to establish the connection with the database.
The code snippet for function class is also provided in the end.
ResultSet rs = null;
String Cid ="cust_id";
String Pno="cust_phone";
String cat="cust_cat";
String start_date="st_date";
String Adv_amt="adv";
String Adv_end="end_date";
String Address="addr";
t2 is the Textfield name which i have used to get entry of customer name. I want to use this customer name as a PK to fetch all the other data about that customer from DB.
rs=f.find(t2.getText());
try{
if(rs.next())
{
t1.setText(rs.getString("cust_id"));
t3.setText(rs.getString("cust_phone"));
t4.setText(rs.getString("cust_cat"));
t5.setText(rs.getString("st_date"));
t6.setText(rs.getString("adv"));
t7.setText(rs.getString("end_date"));
t8.setText(rs.getString("addr"));
}
else
JOptionPane.showMessageDialog(null,"No data for this name");
}
catch(Exception ex)
{
JOptionPane.showMessageDialog(null,ex.getMessage());
}
}
Here is the code snippet for nested class Function which is inside the main class:
class Function{
Connection con=null;
ResultSet rs= null;
PreparedStatement ps = null;
public ResultSet find(String s)
{
try
{
DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
con = DriverManager.getConnection("jdbc:oracle:thin:#Localhost:1521:xe","system","qwerty");
ps= con.prepareStatement("Select * from gkkdb where cust_name='?'");
ps.setString(1,s);
rs= ps.executeQuery();
}
catch(Exception ex)
{
JOptionPane.showMessageDialog(null, ex.getMessage());
}
return rs;
}
}
Please help figure out the problem.
Don't put the parameter placeholder ? in single quotes.
This:
ps = con.prepareStatement("Select * from gkkdb where cust_name='?'");
should be
ps = con.prepareStatement("Select * from gkkdb where cust_name = ?");
The ? is not recognized as a placeholder if you enclose it in single quotes.
Sorting out the bind variable will fix your immediate issue.
You should explicitly specify what columns you want selected and that way you'll only get what you need (someone might add a BLOB column later) and you'll get them in the right order (someone might change the table create script before running on another DB instance, although you are looking up the columns by name, a different order would only impact if you were using positional indexes).
Ditto on the other answer re: bind variables (i.e. no quotes)
Plus, "select * from" is never a good idea, ask your DBA.
Obviously your code is for example, but you should make sure you free up any resources (Connection, Statement, ResultSet) as soon as they are done with. Use Java 7 try-with-resources.
Working with database in java requires a set of lines of code to be written. If the database connection is established again-n-again the same set of lines need to be repeated again-n-again which creates an overhead to programmer.
Hence, I am making a utility class which works as a database agent. The method of this class will be responsible for all the database related stuff from establishing a connection to executing a query and returning the result.
My class goes like this -
package connect;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class Connector
{
private ResultSet rs;
public String password;
public void connect(String dbUrl, String dbClass, String dbUserName, String dbPassword, String query)
{
try
{
Class.forName(this.dbClass).newInstance();
Connection conn = DriverManager.getConnection (dbUrl, dbUserName, dbPassword);
Statement stmt = conn.createStatement();
rs = stmt.executeQuery(query);
while(rs.next())
{
this.password = (String) rs.getObject(1);
}
conn.close();
} //end try
catch(Exception e)
{
e.printStackTrace();
}
}
}
When a programmer needs a query to be executed, below lines can be written for that purpose -
Connector con = new Connector();
con.connect("your database URL",
"your database driver",
"your database username",
"your database password",
"your query");
My question here is that right now I am retreiving the data from ResultSet in the connect method itself. The retreived data can vary from query-to-query hence I want a data structure in which I can store the data from rs in connect() method and return it.
It will look like -
<data structure> result = con.connect("your database URL",
"your database driver",
"your database username",
"your database password",
"your query");
Can someone please suggest me a data structure for this purpose?
Not sure why you're re-inventing this particular wheel, and it seems like if you're repeatedly connecting for every query you're basically writing yourself out of any performance, but why not just use RowSetDynaClass if you're not going to map to objects?
Just be aware that there are a ton of pre-existing solutions that have been tested and proven. And use connection pools; creating connections is expensive.
There is a lot of Open Source, implementation like the one you want to do above.
Spring JDBCTemplate for example.
If you can't use any libraries already available to solve your problem, you could use
Vector<Map<String, Object>>
Where String contains column name and Object is the value of the column. Each element in the Vector corresponds to a row of the ResultSet. This may not be the most efficient data structure but should get the job done.