I'm currently working on this dynamic web project. I have a database and table that I've created in Oracle.
What I need to do right now is have this table connected to my project so that I can retrieve the data from there.
I read that I will need a JDBC driver downloaded and I found it here
But, it's not clear which one is the right one to download and where should I place it after that? in connection pool through admin console?
all toturials I see are related to mySql even this one:
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// JDBC driver name and database URL
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL="jdbc:mysql://localhost/TEST";
// Database credentials
static final String USER = "root";
static final String PASS = "password";
How can I use the same thing for oracle?
It is a example, how to connect to DB and to retrieve data from DB. I hope it is useful for you. Don't forget about try catch finally.
Read this topic.
Closing Database Connections in Java
Class.forName("oracle.jdbc.driver.OracleDriver");
String url = "jdbc:oracle:thin:#127.0.0.1:1521:xe"; //127.0.0.1 = localhost, 1521 = standard port, xe - DB name
String user = "root";
String password = "password";
Connection con = DriverManager.getConnection(url, user, password);
//To create sql query
PreparedStatement preparedStatement = con.prepareStatement("SELECT * FROM person");
//Response of your sql query
ResultSet resultSet = preparedStatement.executeQuery();
//For example you have table (Int id, String firstName, String lastName )
while(resultSet.next()){
//Prepare your data with your program logic....
int id = resultSet.getInt(1);
String firstName = resultSet.getString(2);
String lastName = resultSet.getString(3);
Person p = new Person(id, firstName, lastName);
}
Can you check the JDK version and the JDBC driver version that you are using? Both should be compatible. Check out the FAQ for more information.
Related
This question already has answers here:
com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure
(51 answers)
Closed 3 years ago.
The code below is exactly the same from a YouTube video, but it does not work for me. The expected output is to printout "connected" to the system, which means that JDBC is successfully connected to the database. But I get this error:
com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure
The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.
Here is my code:
package sample;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class Controller {
private static final String username = "root";
private static final String password = "";
private static final String connection = "jdbc:mysql://localhost/hello";
public static void main(String[] args) {
Connection conn = null;
try {
conn = DriverManager.getConnection(connection, username, password);
System.out.println("Connected");
}
catch (SQLException se) {
System.err.println(se);
}
}
}
I've added the JDBC successfully as a library, exactly like the video showed but it doesn't work. I saw similar questions on Stack Overflow but none of them solved my problem. Any help will be appreciated, thanks!
JDBC version: mysql-connector-java-5.1.47-bin.jar
Link failure means DB is not reachable, Kindly confirm your DB host,
port, username and password. If everything is correct, kindly confirm
DB server is running and has yet to hit max connection limit.
and you are using JDBC jar file, this may be corrupted. so check it and I suggest you, import JDBC using Maven
and you did not register JDBC driver. first, register it
by using Class.forName("com.mysql.jdbc.Driver"); this
here is one example for your help,
// JDBC driver name and database URL
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost/EMP";
// Database credentials
static final String USER = "username";
static final String PASS = "password";
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
try{
//STEP 2: Register JDBC driver
Class.forName("com.mysql.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 id, first, last, age FROM Employees";
ResultSet rs = stmt.executeQuery(sql);
//STEP 5: Extract data from result set
while(rs.next()){
//Retrieve by column name
int id = rs.getInt("id");
int age = rs.getInt("age");
String first = rs.getString("first");
String last = rs.getString("last");
//Display values
System.out.print("ID: " + id);
System.out.print(", Age: " + age);
System.out.print(", First: " + first);
System.out.println(", Last: " + last);
}
I assumed you put the appropriate JDBC dependency in your maven file
and use com.mysql.cj.jdbc.Driver as class for newer versions of MySQL-connector
The name of the class that implements java.sql.Driver in MySQL
Connector/J has changed from com.mysql.jdbc.Driver to
com.mysql.cj.jdbc.Driver. The old class name has been deprecated.
I am trying to edit/update details that have been entered into a form. When I try update the address by itself, it works. However when I try update more than one column, it does not. I am assuming there is an issue with the below code as it works with one entity but not more than one.
Update register set (address, contact) = concat('"+address+"', '"+mob+"');
This is the java code. This is error showing, the jsp shows as a blank page
try{
String session_id =null;
HttpSession session1=request.getSession(false);
if(session1!=null){
session_id=(String)session1.getAttribute("name");
}
String name = request.getParameter("name");
String email = request.getParameter("email");
String pass = request.getParameter("password");
String address = request.getParameter("address");
String mob = request.getParameter("contact");
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/alt", "root", "");
Statement stmt = con.createStatement();
stmt.execute("Update register set (address, contact) = concat('"+address+"', '"+mob+"') where uid='"+session_id+"'");
out.println("registration success");
response.sendRedirect("login.jsp");
}catch(Exception e){
}
%>
Try this syntax of update:
update register set
address = concat('"+address+"', '"+mob+"'),
contact = concat('"+address+"', '"+mob+"')
where uid='"+session_id+"'");
i am getting bellow error
[Microsoft][ODBC SQL Server Driver]Connection is busy with results for another hstmt
my code
private static final String DRIVER = "com.microsoft.jdbc.sqlserver.SQLServerDriver";
private static final String URL = "jdbc:odbc:sql2008";
private String[] entity = {"TABLE","VIEW"};
private ResultSet tables,columns,resultSet;
public void getData() throws SQLException, ClassNotFoundException{
Class.forName(DRIVER);
Connection connection=DriverManager.getConnection(URL,USERNAME,PASSWORD);
DatabaseMetaData data = connection.getMetaData();
resultSet = data.getCatalogs();
while (resultSet.next()) {
String dbName = resultSet.getString("TABLE_CAT");
if(dbName.toString().equals("db")){
tables=data.getTables(dbName, "%", "%", entity);
while (tables.next()) {
System.out.println(tables.getString("TABLE_NAME"));
}
}
}
}
URL is DSN connection(connction using dsn name ) and
I am getting this error while trying to fetch tables which is again ResultSet
but its work fine in DSN-less connection that is directly (using address)
You're iterating over two resultsets at the same time:
while (resultSet.next()) {
while (tables.next()) {
According to the error message, this is not allowed.
You could fix it by putting the result of the first iteration in a List<String> databaseNames and then iterating over that list to list the tables.
Alternatively, if you're using SQL Server 2005, you might want to try enabling a feature in SQL Server called "Multiple Active Result Sets".
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";
I have a web application using Java/JSP that was running off a MySQL database which I've now moved to Sybase.
I've changed what I believe are all the relevant connection parts (Sybase Connector and relevant code)
I've been using PreparedStatements for my queries. What was working in MySQL is now no longer returning anything (errors or results).
The first simple query I've been testing is a login form which should be matching the user values for name and password in the table "appuser".
The Prepared Statement in the code provided used to work but no longer does with Sybase.
Relevant code is below. Let me know if anything else is needed.
public void connectDB() throws ClassNotFoundException, SQLException, InstantiationException, IllegalAccessException
{
/* String userName="****";
String password="******";
String url="jdbc:sybase:sybdev1dw/ETL_MON";
Class.forName("com.sybase.jdbc4.jdbc.SybDriver").newInstance();
conn=DriverManager.getConnection(url, userName, password); */
String driver = "com.sybase.jdbc2.jdbc.SybDriver";
String host = "********";
String dbName = "********";
String url = "jdbc:sybase:Tds:" + host + ":4110" +"?SERVICENAME=" + dbName;
String username = "*******";
String password = "*********";
Class.forName(driver);
conn = DriverManager.getConnection(url, username, password);
System.out.println("Connection successful"+conn);
}
public Boolean loginAction(String name, String pass, String role,HttpServletRequest request) throws SQLException {
Boolean valid=false;
session=request.getSession();
PreparedStatement stmt=conn.prepareStatement("SELECT pass FROM appuser WHERE name=?");
stmt.setString(1, name);
results=stmt.executeQuery();
System.out.println("loginAction:"+results.getFetchSize());
while(results.next())
{
if(results.getString("pass").equals(pass))
{
valid=true;
session.setAttribute("name",name);
session.setAttribute("role",role);
}
else
{
valid=false;
}
}
System.out.println("loginAction:"+valid);
return valid;
}
String compare is failing possibly because of spaces being padded to the database column.
result.getString("pass").trim().equals(pass.trim())
One other suggestion. Instead of doing a while(results.next()) , do an if(results.next()) if you are confident it will always return exactly one row ( or zero ).