Click here to Skip to main content
15,887,242 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am trying to display data from two different database,
database1:cover > Table:firmlist
database2:userdata >Table:admin

How to get database connectivity for two different database?

What I have tried:

<%
try {


Class.forName("com.mysql.jdbc.Driver").newInstance();

Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/cover", "root", "");

Statement statement = connection.createStatement();

String QueryString = "SELECT (FirmName)FROM cover.dbo.table firmlist UNION SELECT (UserShortName,UserPW) from userdata.dbo.table admin WHERE FirmId=UserId ";;
ResultSet rs = statement.executeQuery(QueryString);
%>


<TABLE id="myTable" cellpadding="15" style="background-color: #b9d9e8;">
<TR>

<TH>Company Name</TH>
<TH>User Name</TH>
<TH>Password</TH>
</TR>
<%
while (rs.next()) {
%>

<TR>
<TD><%=rs.getString(2)%></TD>
<TD><%=rs.getString(3)%></TD>
<TD><%=rs.getString(4)%></TD>
</TR>
<% } %>
<%

rs.close();
statement.close();
connection.close();
} catch (Exception ex) {
%>


<%
out.println(ex);
}
%>
</TABLE>
Posted
Updated 29-Mar-18 7:30am

1 solution

First problem:
You're trying to UNION two sets with a different number of columns. You can only UNION sets with the same number of columns:
MySQL :: MySQL 5.7 Reference Manual :: 13.2.9.3 UNION Syntax[^]

I suspect you want to JOIN the tables instead:
MySQL :: MySQL 5.7 Reference Manual :: 13.2.9.2 JOIN Syntax[^]

Second problem:
You're specifying a three-part name for the tables - cover.dbo.table and userdata.dbo.table. That's MS SQL Server syntax, not MySQL syntax.

SQL
SELECT FirmName, UserShornName, UserPW FROM cover.table As firmlist JOIN userdata.table As admin ON admin.UserId = firmlist.FirmId


Third problem:
You appear to be storing passwords in plain text. Don't do that.
Secure Password Authentication Explained Simply[^]
Salted Password Hashing - Doing it Right[^]
 
Share this answer
 
Comments
Member 13752376 30-Mar-18 2:13am    
Thank You so much sir...I am beginner for coding
i have replaced my select query with your query but error occur like java.lang.ClassNotFoundException: com.mysql.jdbc.Driver

because FirmName column is from firmlist table under the cover database,and UsershortName ,UserPW column is from admin table under userdata database
Richard Deeming 3-Apr-18 14:08pm    
A "class not found" exception is nothing to do with your SQL query!

Try some of the suggestions from this thread[^.
Member 13752376 30-Mar-18 2:17am    
how can i open connection for 2 different database in following code:
Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/cover", "root", "");

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900