I'm new to Java and I want to connect with MySQL local server, but it's throwing an exception error. How can I fix the code?
Connection information:
Lport:3306
database name= siba_1
table name= test_1
Code:
package java_recap;
import java.sql.*;
public class Java_recap {
public static void main(String[] args) {
try{
Class.forName("com.mysql.jdbc.Driver");
Connection
con=DriverManager.getConnection("jdbc:mqsql://localhost:3306/siba_1","root","");
Statement stn=con.createStatement();
ResultSet rs=stn.executeQuery("select * from test_1");
while(rs.next()){
System.out.println(rs.getString(1)+" "+rs.getString(2));
}
}
catch(Exception e){
System.out.println("e");
}
}
}
DriverManager is a old way of doing things. if you still want to use DriverManger then:
Need mysql dependency add jar on classpath or use maven like below :
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.19</version>
</dependency>
Now Let's see how we can connect to our database and execute a simple select-all through a try-with-multiple-resources:
String sql = "select * from test_1";
String connectionUrl = "jdbc:mysql://localhost:3306/siba_1?
serverTimezone=UTC";
try (Connection conn = DriverManager.getConnection(connectionUrl,
"root", "");
PreparedStatement ps =
conn.prepareStatement(sql);
ResultSet rs = ps.executeQuery()) {
while (rs.next()) {
System.out.println(rs.getString(1)+" "+rs.getString(2));
// do something with the extracted data...
}
} catch (SQLException e) {
// handle the exception
}
Other way : The better way is to get a DataSource either by looking one up that your app server container already configured for you:
Context context = new InitialContext();
DataSource dataSource = (DataSource) context.lookup("java:comp/env/jdbc/siba_1");
or instantiating and configuring one from your database driver directly:
MysqlDataSource dataSource = new MysqlDataSource();
dataSource.setUser("root");
dataSource.setPassword("");
dataSource.setServerName("localhost");
and then get connections from it, same as above:
Connection conn = dataSource.getConnection();
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("select * from test_1");
...
rs.close();
stmt.close();
conn.close();
Related
I am using h2 in memory database for testing. I have a situation where nested database calls will happen. Using h2 the connection is getting closed on the nested call, even if the objects are different.
ClassA:
Public class TestDb {
Public String getById(String id) {
try {
Connection conn= getConnection();
PreparedStatement ps = conn.prepareStatement(“query”);
ResultEntity rs = ps.executeQuery();
getOthersById(rs.get(id));
//here rs is closed and seering error as: object is closed
rs.get(2);
}Catch(Exception ex) {
//handle exceptions
}finally {
// close resultset
//close ps
// close conn
}
}
public int getOthersById(String id) {
try {
//get new connection
Connection conn= getConnection();
PreparedStatement ps = conn.prepareStatement(“query”);
ResultEntity rs = ps.executeQuery();
rs.get(id);
}Catch(Exception ex) {
//handle exceptions
}finally {
// close resultset
//close ps
// close conn
}
}
}
The problem in h2 is after the closing new connection and result set in getOthersById method, resultSet in getById is closed.
I am creating the h2 as below:
jdbc:h2:mem:test;DB_CLOSE_ON_EXIT=FALSE;DB_CLOSE_DELAY=-1;
private void rtrBtnActionPerformed(java.awt.event.ActionEvent evt) {
DefaultTableModel model = (DefaultTableModel) depTbl.getModel();
try{
Class.forName("java.sql.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost/test1","admin","root");
Statement stmt = con.createStatement();
String query = "SELECT * FROM dept;";
ResultSet rs = stmt.executeQuery(query);
while(rs.next()){
String dno = rs.getString("deptno");
String dName = rs.getString("dname");
String lc = rs.getString("loc");
model.addRow(new Object[] {dno,dName,lc});
}
rs.close();
stmt.close();
con.close();
}
catch(Exception e){
JOptionPane.showMessageDialog(null,"Error In Connectivity");
}
}
Im trying to connect my JForm to the mysql database but not able to connect to the database, continuously executing catch statement "Error in Connectivity", please help how should i resolve this issue..............................................................................
Change the following line
Class.forName("java.sql.Driver");
to
Class.forName("com.mysql.jdbc.Driver");
in your code
This line of code is not correct - Class.forName("java.sql.Driver");
The java.sql.Driver is an interface. You need to provide the correct jdbc driver class for you appropriate db.
Such as for Oracle - Class.forName("oracle.jdbc.driver.OracleDriver");
I'm trying to connect to an Oracle database using JDBC Driver and I'm handle with an error: "java.sql.SQLException: Invalid Oracle URL specified".
My code is the following:
import java.sql.*;
public class L9
{
public static void main(String args[])
{
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con = DriverManager.getConnection("jdbc:oracle:thin;#localhost:1521:xe","user","password");
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("select * from table");
while(rs.next())
System.out.println(rs.getInt(1) + " "+rs.getString(2)+ " "+rs.getString(3));
con.close();
}
catch(Exception e)
{
System.out.println(e);
}
}
}
Anyone knows what is the problem?
It should be
jdbc:oracle:thin:#localhost:1521:xe
instead of
jdbc:oracle:thin;#localhost:1521:xe
(note the : after the "thin")
It is better to use a long format connection URL where you have the ability to pass connection descriptors. Easy Connection URL (jdbc:oracle:thin:#//localhost:1521/myorcldbservicename) ) does establish the connection but does not provide any High Availability capabilities.
jdbc:oracle:thin:#(DESCRIPTION=(ADDRESS=(HOST=myhost)(PORT=1521)(PROTOCOL=tcp))(CONNECT_DATA=(SERVICE_NAME=myorcldbservicename)))
I want to access to NexusDB V3 with Java.
So I have a Java project with many files that connects to the database. Can anyone tell me if it is possible to use a Java class file for connecting to the database.
I've tried JDBC connector and the ODBC connector but nothing is working.
I have read about a bridge between them but I don't know how to make it so please help.
public class dbConnect {
public static void connect(){
Connection conn;
Statement stmt;
ResultSet rs;
String sql;
conn = null;
String url = "jdbc:mysql://localhost:3306/db_oopproject";
try{
Class.forName(driver).newInstance();
conn = DriverManager.getConnection(url,"user","12345");
stmt = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
sql = "Select * from user_account";
rs = stmt.executeQuery(sql);
}
catch (Exception e){
System.out.print(e.getMessage());
}
}
}
first off, your url contains "mysql", are you sure that will work for the jdbc bridge to connect to NexusDB?
I don't know why i am getting this error infact i write code write and also add java connector in my project.
Please any one resolve my issue
import java.sql.*;
public class jbdcdemo {
public static void main(String[] args) {
try{
//1. Get Connection to DB
Connection myConn = DriverManager.getConnection("jbdc:msql://localhost:3306/world","root","1234");
//2. Create a statement
Statement myStmt = myConn.createStatement();
//3. Execute sql query
ResultSet myRs = myStmt.executeQuery("SELECT * FROM world.city;");
//4. Process the results
while(myRs.next()){
System.out.println(myRs.getString("Name")+", "+myRs.getString("District"));
}
}
catch(Exception exc){
exc.printStackTrace();
}
}
}
Try fixing the connection string:
Connection myConn = DriverManager.getConnection("jdbc:mysql://localhost:3306/world","root","1234")
Looks like you have semicolon for the sql statement,
Below is the correct one.
ResultSet myRs = myStmt.executeQuery("SELECT * FROM world.city");