Function which returns connection variable - java

In my Java application I have such code:
private static OracleDataSource oracleDatasource;
public static OracleConnection getConnection() throws SQLException
{
final OracleConnection conn = (OracleConnection) oracleDatasource.getConnection("user", "password");
return conn;
}
I would like to write equivalent of such function in Postgres JDBC. I know that I could use this line
private static PGSimpleDataSource postgresDatasource;
to define data source. But how can I define and return connection variable like it was in Oracle?

Related

Connect JDBC to IP address [duplicate]

This question already has answers here:
Connect Java to a MySQL database
(14 answers)
Closed 4 years ago.
I'm having issues connecting to an external IP address using JDBC. When I execute the following code, I get this error No suitable driver found for jdbc:mysql://52.206.157.109:3306/U054Jk
Code:
package util;
import java.sql.*;
public class db {
private static String server = "52.206.157.109";
private static String dbName = "U054Jk";
private static String userName = "secret";
private static String password = "secret";
private static Connection getCon() throws SQLException {
String host = "jdbc:mysql://" + server + ":3306/" + dbName;
Connection conn = DriverManager.getConnection(
host,
userName,
password
);
return conn;
}
public static ResultSet ExecQuery(String query) throws SQLException {
//Get the connection
Connection conn = getCon();
//Create the statement
Statement stmt = conn.createStatement();
//Execute the statement
ResultSet rs = stmt.executeQuery(query);
//Return ResultSet
return rs;
}
}
I can connect with my SQL client just fine using the credentials but can't quite figure out the JDBC string that I need for the URL. Thank you for your help.
Please add MySQL Connector in the classpath. Your project needs a JDBC driver implementing the interfaces of JDBC.
If you are using Apache Maven, add the following in the pom.
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.13</version>
</dependency>
Or else, download the jar from the link and add it to the classpath.

How to get MariaDB connection using java?

I worked on mysql server and connected my java applications successfully. And now I changed to MariaDB. How to connect with MariaDB server using java?
How this should be changed?
public class DBConnection {
private Connection connection;
private static DBConnection dBConnection;
public DBConnection() throws ClassNotFoundException, SQLException {
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/db", "root", "mysql");
}
public static DBConnection getDBConnection() throws ClassNotFoundException, SQLException {
if (dBConnection == null) {
dBConnection = new DBConnection();
}
return dBConnection;
}
public Connection getConnection() {
return connection;
}
}
Minor changes for MariaDB are as follows: Use the MariaDB Connector/J with the following Driver class:
org.mariadb.jdbc.Driver
For DB Connection use the following structure:
jdbc:(mysql|mariadb)://host:port/[database]
Therefore, your code as above would only require the change for
Class.forName("org.mariadb.jdbc.Driver");
and the rest would work well since MySQL and MariaDB clients are compatible.After all, MariaDB is an enhanced, drop-in replacement for MySQL.
More information about connecting to MariaDB using the Java Connector can be accessed from MariaDB Knowledge Base (MariaDB Connector/J

Database connection in Java Servlet [duplicate]

This question already has answers here:
How to install JDBC driver in Eclipse web project without facing java.lang.ClassNotFoundexception
(13 answers)
Closed 7 years ago.
I'm trying to connect to a database in a Java Servlet, but I am unable to connect. I searched on google and each website is showing different way I don't know why.
Here is the code that I tried to connect, but nothing(data) is going to MySQL database rows.
public class DBConnection{
private static final long serialVersionUID = 1L;
private final Connection connection;
private final String dbURL = "jdbc:mysql://localhost:3306/Servlet";
private final String user = "root";
private final String pwd = "";
public DBConnection() throws ClassNotFoundException, SQLException{
Class.forName("com.mysql.jdbc.Driver");
this.connection = DriverManager.getConnection(dbURL, user, pwd);
}
public Connection gC(){
return this.connection;
}
}
Here is I'm trying to insert data in database (but data is not adding to DB).
public class ReServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
try{
String uName=req.getParameter("uName");
String uEmail=req.getParameter("uEmail");
String uPass=req.getParameter("uPass");
DBConnection conn=new DBConnection();
PreparedStatement ps;
ps = conn.gC().prepareStatement("insert into users(name,email,password) values (?,?,?)");
ps.setString(1, uName);
ps.setString(2, uEmail);
ps.setString(3, uPass);
ps.execute();
}catch(SQLException | ClassNotFoundException se){
se.printStackTrace();
}finally{
}
}
}
I also request to all, please give me simple and easy database connection example, about each website is showing with full registration or any other system. But I just want simple db connection example as I am trying in my code.
Edited
By replacing se.printStackTrace(); to this throw new RuntimeException(se); I'm getting this Exception java.lang.RuntimeException: java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
You nedd to register your driver with DriverManager like this:
Class c = Class.forName("com.mysql.jdbc.Driver");
DriverManager.registerDriver( c.newInstance() );
Please remember to close your connection in finally block.

Java SQL Derby Getconnection illegal modifier

I have been learning how to get SQL Derby installed and running, and I looked at google and didn't find anything useful that could fix this problem. In the line: Connection getConnection() I get the error: "Illegal modifier for parameter getConnection; only final is permitted" What is wrong? It gives me the same error even if I move the code over to a different class. It is derby on eclipse in java, and I did everything in creating and connecting the database. I have not imported any reference libraries or software pluggins. I updated the DTP. I used the vogella tutorial for databases and eclipse. I have also installed Derby several times over the course of a couple months, but never seem to be able to get a separate java project to connect properly. Once again, my issue is the getConnection giving me an error. I have a comment in the area of the problem.
import java.sql.Connection;
import java.util.Properties;
public class main {
public static void main(String[] args)
{
// TODO Auto-generated method stub
//******************************************************
//The issue is the getConnection()
public Connection getConnection() throws SQLException {
//*******************************************************
Connection conn = null;
Properties connectionProps = new Properties();
conn = DriverManager.getConnection("jdbc:derby:C:\\Users\\Josiah\\MyDB", connectionProps);
System.out.println("Connected to database");
return conn;
}
}
}
You are trying to define your getConnection method nested inside the main method - this is not allowed in Java.
Move the method to be outside of main:
public class main {
public static void main(String[] args)
{
... main method code
}
public Connection getConnection() throws SQLException {
Connection conn = null;
Properties connectionProps = new Properties();
conn = DriverManager.getConnection("jdbc:derby:C:\\Users\\Josiah\\MyDB", connectionProps);
System.out.println("Connected to database");
return conn;
}
}

Java mySQL remote connection through JDBC: ODBC bridge

I am having problems remotely connecting to my mySQL database in Java. Here is my error message:
java.sql.SQLException: [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified
I am sure my ip address & port I am using work, since I am using the same ip & port for a mySQL client program.
My hosting company do not support JDBC so I am using a JDBC-ODBC bridge.
Here is my class:
public class SQLdataBase {
private Connection con;
private Statement st;
private static final String url="jdbc:odbc://xxx.xxx.xxx.xxx:3306";
private static final String className="sun.jdbc.odbc.JdbcOdbcDriver";
private static String user;
private static String pass;
SQLdataBase(String userName, String password) {
user=userName;
pass=password;
try {
Class.forName(className);
con = DriverManager.getConnection(url, user, pass);
System.out.println("success");
st = con.createStatement();
} catch (Exception ex) {
System.out.println(ex);
}
//do whatever database processing is required
}
public void queryNoReturn(String query) throws SQLException{
st.executeQuery(query);
}
}
The error occures at this line:
con = DriverManager.getConnection(url, user, pass);
What am I doing wrong?
String url="jdbc:odbc://xxx.xxx.xxx.xxx:3306";
In ODBC, you normally use the data source name (DSN) instead of hostname:port in URL. If this is unclear and/or not directly revealable in the documentation of the hosting, then you'll need to contact them for the exact DSN. Once known, then use the following URL:
String url="jdbc:odbc:dataSourceName";

Categories

Resources