I am using a code like that to connect to database in Java:
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
String url = "jdbc:mysql://localhost:3306/mydb";
String user = "root";
String password = "Pass";
I get data from database by executing sql query:
String sqlQuery = "Select queryID from test_data_solution";
rs = stmt.executeQuery(sqlQuery);
...
But I need to connect another database model in MySQL server. I will use inner join from a table which is in another database. How can I connect to or get data from another database in the same Java program? I want to run the code like:
select *
from mydb.test_data_solution
inner join anotherdb.queryid_tokensid
on test_data_solution.queryid = queryid_tokensid.queryid
You can reference tables by specifying the database they are in and do cross-database queries. E.g.
String sqlQuery = "Select t.queryID, x.someCol from mydb.test_data_solution t JOIN otherdb.some_table x ON t.queryID = x.queryID";
Related
I'm trying to execute multiple sql commands, but it gives me "error in your SQL syntax;"
Db_Connection dbconn = new Db_Connection();
Connection myconnection = dbconn.Connection();
String sqlString = "SELECT DISTINCT std_id FROM std_crs WHERE crs_id ='222123'; "
+ "SELECT * FROM cplus_grades ;";
Statement myStatement = myconnection.createStatement();
boolean results = myStatement.execute(sqlString);
do {
if (results) {
ResultSet rs = myStatement.getResultSet();
while (rs.next()) {
}
rs.close();
}
results = myStatement.getMoreResults();
} while(results);
myStatement.close();
I did a small test with three JDBC drivers:
MS SQL: works, returns two result sets
MySQL: fails with a syntax error - that is what you are seeing
HSQLDB: runs, but returns only one result set.
So I guess it simply depends on the JDBC driver if this technique works. Maybe it works only in MS SQL JDBC.
UPDATE:
It also works with Postgres.
please
1. String dbUrl = "jdbc:mysql://yourDatabase?allowMultiQueries=true";
this should be your jdbc connection url
I am trying to connect to database in Java. It's a simple program.
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost/servlets","root","");
smt = con.createStatement();
query = "select pass from users where uname = "+uname;
System.out.println(query);
rs = smt.executeQuery(query);
if((rs.getString("pass"))==pass){
out.println("correct pass...logged in..");
}
else {
out.println("Incorrect pass...not logged in..");
}
But it says
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an
error in your SQL syntax; check the manual that corresponds to your
MariaDB server version for the right syntax to use near '#gmail.com'
at line 1
I am trying to verify the password for a particular email-id.
At this line
query = "select pass from users where uname = "+uname;
You have not quoted the uname, so if the value is name#gmail.com this results in a syntax error. I.e. the actual statement being sent to the DB is
select pass from users where uname = name#gmail.com
which is invalid. You should be using PreparedStatement instead
query = "select pass from users where uname = ?";
PreparedStatement ps = con.prepareStatement(query);
ps.setString(1,uname);
ResultSet rs = ps.executeQuery();
Replace this
query = "select pass from users where uname = "+uname;
to
query = "select pass from users where uname = "'+uname+'" ";
or try
query = "select pass from users where uname = ? ";
i have 2 PostgreSQL databases on different port: DB1 on port 5432 and DB2 on port 5431
and i have code to get data from DB1 like this :
try {
Class.forName("org.postgresql.Driver");
String conString = "jdbc:postgresql://127.0.0.1:5432/DB1?user=MyUser&pass=MyPass" ;
c = DriverManager.getConnection(conString);
st = c.createStatement();
ResultSet rs = st.executeQuery(query);
while (rs.next()){
vaArrL.add(rs.getDouble("va"));
vbArrL.add(rs.getDouble("vb"));
vcArrL.add(rs.getDouble("vc"));
}
and work good when i send singe query to DB1 only.
but now, i have query to both databases together like :
select va, vb from DB1.public.t1 where datatime >= 1417384860 and datatime <= 1417381199
union
select va, vb from dblink('hostaddr=127.0.0.1 port=5431 dbname=DB2 user=MyUser password =MyPass '::text,
'select va, vb
from Db2.public.t2 order by datatime ')
datos(va integer,vb integer);
when i run query from pgAdmin i get result
but when i sent query to gunction i get : connection not available
Now. How can i send my query to function and i get values?
Can you try using JDBC's setCatalog method?
setCatalog's javadoc states that:
Calling setCatalog has no effect on previously created or prepared
Statement objects. It is implementation defined whether a DBMS prepare
operation takes place immediately when the Connection method
prepareStatement or prepareCall is invoked. For maximum portability,
setCatalog should be called before a Statement is created or prepared.
try {
Class.forName("org.postgresql.Driver");
// Connect to DB1 (specified in connection string/URL).
String conString = "jdbc:postgresql://127.0.0.1:5432/DB1?user=MyUser&pass=MyPass" ;
c = DriverManager.getConnection(conString);
st = c.createStatement();
// Execute query on DB1.
ResultSet rs = st.executeQuery(query);
while (rs.next()){
vaArrL.add(rs.getDouble("va"));
vbArrL.add(rs.getDouble("vb"));
vcArrL.add(rs.getDouble("vc"));
}
// Switch to DB2 and execute query.
c.setCatalog("DB2");
Statement st2 = c.createStatement();
ResultSet rs2 = st2.executeQuery(...);
}
If the JDBC driver doesn't support setCatalog, then you can execute the SQL query USE DB2 explicitly but this might affect already open statements (I'm not sure about this).
Edit: OP wants all results from both databases in the same ResultSet.
Assuming that DB1 and DB2 are on same server, I'd recommend creating a view in database DB1 which can access tables in database DB2 and return combined results. Then you can just SELECT * from the view via JDBC and get the results.
You can use a query like this for your view (assuming that the view is created in DB1):
SELECT all.va, all.vb FROM
(SELECT va, vb, datatime FROM t2
UNION
SELECT va, vb, datatime FROM DB2.public.t2) all
ORDER BY all.datatime
Note: To access a table in another database, you need to specify [db-name].[schema].[tablename].
If your query needs dynamic arguments, then you can create a stored procedure instead of a view.
i am find 1 solution
i am use 2 connection and send to query from client to xmlrpc server, here :
String conString = "jdbc:postgresql://" + host + ":" + port + "/" + DBName +
"?user=" + user + "&pass=" + pass;
String conString1 = "jdbc:postgresql://" + host + ":" + port2 + "/" + DBName2 +
"?user=" + user + "&pass=" + pass;
c = DriverManager.getConnection(conString);
c2 = DriverManager.getConnection(conString1);
st = c.createStatement();
st2 = c2.createStatement();
List<ResultSet> resultSets = new ArrayList<>();
resultSets.add(st.executeQuery(query));
resultSets.add(st2.executeQuery(query2));
ResultSets rs = new ResultSets(resultSets);
while (rs.next()){
unbArrL.add(rs.getUnbalance("unbalance"));
}
and resultSets class to get values from DB is :
class ResultSets {
private java.util.List<java.sql.ResultSet> resultSets;
private java.sql.ResultSet current;
public ResultSets(java.util.List<java.sql.ResultSet> resultSets) {
this.resultSets = new java.util.ArrayList<>(resultSets);
current = resultSets.remove(0);
}
public boolean next() throws SQLException {
if (current.next()) {
return true;
}else if (!resultSets.isEmpty()) {
current = resultSets.remove(0);
return next();
}
return false;
}
public Double getUnbalance(String unbalance) throws SQLException{
return current.getDouble("unbalance");
}
}
I am trying check if a certain key exists in the database before i try to add a student whom might have the same key. I have a class called DataBaseHandler which has functions to manipulate the database, The studentAlreadyExist function returns true if the given id is present and false if not. When I try to run the application it gives me this error
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '?' at line 1
*******
Here is my code snippet for testing if a student exist
//check if the student exist
public boolean studentAlreadyExists(String id) throws SQLException{
//first connect to the database;
connectToDataBase();
selectSQL = "select name from student where idNumber like ?";
prstmt = con.prepareStatement(selectSQL);
prstmt.setString(1, id);
ResultSet rs = prstmt.executeQuery(selectSQL);
String dbname = null;
while(rs.next()){
dbname = rs.getString("name");
}
return dbname != null;
}
You've prepared it before, you don't have to deliver the queryString again as parameter.
API:
https://docs.oracle.com/javase/7/docs/api/java/sql/PreparedStatement.html#executeQuery()
Should look like:
public boolean studentAlreadyExists(String id) throws SQLException{
connectToDataBase();
selectSQL = "select name from student where idNumber like ?";
prstmt = con.prepareStatement();
prstmt.setString(1, id);
/* Executes the SQL query in this PreparedStatement object and returns the ResultSet object generated by the query.*/
ResultSet rs = prstmt.executeQuery();
String dbname = null;
while(rs.next()){
dbname = rs.getString("name");
}
return dbname != null;
}
Don't pass the selectSQL as a parameter (again) when you perform executeQuery.
I have a mysql database that I am trying to retrieve from our website host (godaddy). I followed a format that seems to be right but it tells me that:
java.sql.SQLException: No database selected
Code:
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 database...");
conn = DriverManager.getConnection(DB_URL, USER, PASS);
// STEP 4: Execute a query
System.out.println("Creating statement...");
stmt = conn.createStatement();
String sql;
sql = "SELECT * FROM item_master";
ResultSet rs = stmt.executeQuery(sql); //<-- This is where the error is.
// STEP 5: Extract data from result set
while (rs.next()) {
// Retrieve by column name
int id = rs.getInt("id");
// Display values
System.out.print("ID: " + id);
}
...
}
I did a print statement of the conn to maybe think the connection could of been null and was shown this:
com.mysql.jdbc.JDBC4Connection#2a6*****
Anyone have any ideas what could cause something like this?
Your URL for your database should include your database name. This is normally your URL followed by a "/DBNAME".
String URL = "jdbc:mysql://localhost:3306/mydb";
Where "mydb" is your database name.
What is the value of DB_URL? As far as I am aware, the URL needs to be of the form:
"WEBURL/DATABASENAME:PORT"
Are you just trying to connect to the WEBURL, without specifying a DATABASE?
I had the same problem.
Just run one more query (before your 'SELECT' statement) to connect to your database.
First:
sql = "USE <yourdatabase>";
ResultSet rs = stmt.executeQuery(sql);
And after:
sql = "SELECT * FROM item_master";
rs = stmt.executeQuery(sql);