I created a connection to a mysql database. Below is my code
package org;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.ResultSet;
public class DatabaseConn {
public static void main(String[] args) {
System.out.println("Loading driver...");
try {
Class.forName("com.mysql.jdbc.Driver");
System.out.println("Driver loaded!");
} catch (ClassNotFoundException e) {
throw new IllegalStateException("Cannot find the driver in the classpath!", e);
}
try {
String host = "jdbc:mysql://localhost:3306/sys";
String username = "root";
String password = "root";
Connection Con = DriverManager.getConnection(host, username, password);
Statement stmnt = Con.createStatement();
String SQL = "SELECT * FROM sys_config";
ResultSet rs = stmnt.executeQuery( SQL );
System.out.println("Records:"+rs);
} catch (SQLException err) {
System.out.println(err.getMessage());
}
}
}
My Understanding towards Interface implementation on classes says, Interface type reference to an object of class that implements Interface.
But when I investigated below code snippet used in above code..
Connection Con = DriverManager.getConnection(host, username, password);
DriverManager.getConnection(host, username, password) returns a reference(of type Connection) to a object but no interface is implemented in class DriverManager. Can anyone clear my this doubt ..? Or I missed out anything ?
Same thing am not able to get with below code snippet
Statement SQL = Con.createStatement();
Con.createStatement() should return a reference to a object that implements Statement interface. But this Connection interface is implemented by ConnectionImpl class where implementation is present like below
public class ConnectionImpl
extends ConnectionPropertiesImpl
implements Connection {
public Statement createStatement()
throws SQLException
{
return createStatement(1003, 1007);
}
public Statement createStatement(int resultSetType, int resultSetConcurrency)
throws SQLException
{
checkClosed();
StatementImpl stmt = new StatementImpl(this, this.database);
stmt.setResultSetType(resultSetType);
stmt.setResultSetConcurrency(resultSetConcurrency);
return stmt;
}
}
Let's look at this bit by bit:
DriverManager.getConnection(host, username, password) returns a reference (of type Connection) to a object...
This is correct.
...but no interface is implemented in class DriverManager.
This is also correct.
What your explanation is missing is that DriverManager.getConnection() doesn't return a reference to the DriverManager. It returns a reference to an object of a different class, one that does implement the Connection interface.
Let's say for the sake of argument that there is a class called MySqlConnection:
class MySqlConnection implements Connection {
...
}
Now, DriverManager.getConnection() could well return an instance of this class:
class DriverManager {
public Connection getConnection(...) {
return new MySqlConnection(...);
}
}
Hope this clears things up.
getConnection and createStatement are factory methods. Note that the interface is implemented in the returning object class.
Only the interfaces like DriverManager, Connection , Statement etc. are declared in the JDK , the concrete classes which implement them are there in the corresponding JDBC driver you use. For ex., in your case it is mysql jdbc driver added in your class path. So, it is these concrete implementations in the driver jar that knows how to connect to the Database and talk to it. JDK has just defined the specification in the form of interfaces that all the vendor classes should implement. This makes the java code independent of any change in the Database and the corresponding driver.
Related
This question already has answers here:
Connect Java to a MySQL database
(14 answers)
Closed 1 year ago.
am getting an exception as java.sql.Connection.prepareStatement(String) because con is null, I don't know why as I have already added MySQL Connector jar file.
import java.sql.Connection;
import java.sql.PreparedStatement;
public class Studentdao {
public static boolean insertStudenttoDB(Student st) {
boolean f=false;
try {
Connection con =CP.createc();
//jdbc code
String q="insert into students(sname,sphone scity)values(?,?,?)";
PreparedStatement pstmt=con.prepareStatement(q);
pstmt.setString(1,st.getStudentname());
pstmt.setString(2,st.getStudentcity());
pstmt.setLong(3,st.getStudentphone());
//execute
pstmt.executeUpdate();
f=true;
}
catch(Exception e) {
e.printStackTrace();
}
return f;
}
}
This is my connection program
import java.sql.Connection;
import java.sql.DriverManager;
public class CP {
static Connection con;
//load driver
public static Connection createc() {
try {
Class.forName("com.sql.jdbc.Driver");
//creating connection
String user="mysql";
String password="mysql";
String url="jdbc:mysql://localhost:3306/student_manage";
con=DriverManager.getConnection(url,user,password);
}catch(Exception e) {
e.printStackTrace();
}
return con;
}
}
Incorrect class name
You appear to have an incorrect class name, if you are using the Connector/J product as your JDBC driver.
Section 3.6.1 of the Connector/J manual shows the use of "com.mysql.cj.jdbc.Driver" versus your use of "com.sql.jdbc.Driver". Here is their code example:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
// Notice, do not import com.mysql.cj.jdbc.*
// or you will have problems!
public class LoadDriver {
public static void main(String[] args) {
try {
// The newInstance() call is a work around for some
// broken Java implementations
Class.forName("com.mysql.cj.jdbc.Driver").newInstance();
} catch (Exception ex) {
// handle the error
}
}
}
DataSource
Note that your use of Class.forName is generally not needed in modern Java. The JDBC architecture was years ago revamped so that now drivers are automatically located and loaded using the Java Service Provider Interface (SPI) technology.
I do suggest you make a habit of using a DataSource to obtain connections rather than calling on the DriverManager. Using DataSource makes your code much more flexible. You will be able to switch JDBC drivers, add connection pooling, and externalize configuration info (server address, database name, user name, password, etc.) for deployment.
Usually your JDBC driver comes with a basic implementation of DataSource. Check the documentation for all the various options you can set, specific to your database (MySQL in this case).
For MySQL, I understand the implementation of DataSource currently provided in Connector/J is com.mysql.cj.jdbc.MysqlDataSource. Caveat: I make regular use of Postgres & H2, not MySQL, so I may not be up-to-date.
See my Answer to another Question for source code of a full example of connecting and working with MySQL. Here are the parts relating to DataSource and Connection.
private DataSource configureDataSource ( )
{
System.out.println( "INFO - `configureDataSource` method. " + Instant.now() );
com.mysql.cj.jdbc.MysqlDataSource dataSource = Objects.requireNonNull( new com.mysql.cj.jdbc.MysqlDataSource() ); // Implementation of `DataSource` bundled with H2.
dataSource.setServerName( "db-mysql-sfo3-422-do-user-8982-1.x.db.ondigitalocean.com" );
dataSource.setPortNumber( 24_090 );
dataSource.setDatabaseName( "defaultdb" );
dataSource.setUser( "scott" );
dataSource.setPassword( "tiger" );
return dataSource;
}
Early in the lifecycle of your app, instantiate and retain the DataSource object returned from that method. Remember, a DataSource holds only the configuration details; it is not an open resource itself, and need not be closed.
DataSource dataSource = this.configureDataSource();
To open a connection, pass the DataSource to your method that wants to connect to the database.
private void dumpTable ( DataSource dataSource ) { … }
Here is a piece of that dumpTable method.
Notice the use of try-with-resources syntax to automatically close the open resources in the order in which they were declared, even in case of failure with exceptions being thrown.
String sql = "SELECT * FROM event_ ;";
try (
Connection conn = dataSource.getConnection() ; // 🡄 Use the passed `DataSource` object to ask for a `Connection` object.
Statement stmt = conn.createStatement() ;
ResultSet rs = stmt.executeQuery( sql ) ;
)
{
…
}
catch ( SQLException e )
{
e.printStackTrace();
}
here's the code I tried to connect java class with mysql. Make sure you have to add the required driver to your libraries.
import java.sql.Connection;
import java.sql.DriverManager;
public class Server {
public static Connection getConnection()
{
try
{
Class.forName("com.mysql.jdbc.Driver");
String urls = "127.0.0.1";//you can even replace this with localhost
String username = "yourusername";
String password = "1234";
Connection conn = DriverManager.getConnection("jdbc:mysql://"+urls+":3306/yourdb?useUnicode=yes&characterEncoding=UTF-8", username, password);
return conn;
}
catch(Exception e)
{
e.printStackTrace();
}
return null;
}
Im trying to create web app using java and mariadb but i encountered problem when tried to implement mariadb to login. Here my code:
initSql:
package dao;
import java.sql.Connection;
import java.sql.DriverManager;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
#WebServlet("/initSql")
public class initSql extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public initSql() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see Servlet#init(ServletConfig)
*/
Connection conn = null;
public void init(ServletConfig config) throws ServletException {
// TODO Auto-generated method stub
try {
Class.forName("org.mariadb.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mariadb://localhost:3306/baza_new", "root","root");
System.out.println("db povezana");
}catch(Exception e){
//JOptionPane.showMessageDialog(null, e);
System.out.println("db NIiiJE povezana");
//return null;
}
}
}
LoginDAO:
package dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import dao.initSql;
public class LoginDAO {
static Connection con = null;
public static boolean validate(String username, String password, String type) {
boolean status = false;
try {
con = initSql.init();
System.out.println("1");
String query = "select * from users where username=? and password=?";
PreparedStatement pst = con.prepareStatement(query);
//pst.setString(1, type);
pst.setString(1, username);
pst.setString(2, password);
ResultSet rs = pst.executeQuery();
status= rs.next();
con.close();
}catch(Exception e) {System.out.print(e);}
return status;
}
}
and i get markers:
Cannot make static reference to non-static method from type generic servler
Type mistmatch cannot connect from void to Connection
I'm little bit stuck with this problem.Can someone help me with my code?
People seem to be neglecting the more broad-scale issues in your code. There are standards to follow like capitalization etc but overall you have some bigger issues.
You shouldn't be making erroneous instances of initSql as it's an HttpServlet, it just doesn't make sense. You also have static/non-static references to a Connection field when you don't need it. To start with, change initSql#init to return a Connection, and while I normally wouldn't recommend abusing static this way, make the method itself static:
//returns a connection, requires no class instance
public static Connection init(ServletConfig config) { ... }
From there, we can now retrieve a Connection instance by calling this method:
Connection con = initSql.init();
Overall you should have a proper class or design for handling this, but for simple learning this is "okay".
Secondly, you're not quite using ResultSet correctly. #next will determine if there is an available row to point to from the SQL results, and if so it moves the marker to the next row. You would use it in order to check if you can retrieve results:
ResultSet set = /* some sql query */;
String someField;
if (set.next()) {
//gets the value of the column "my_field"
someField = set.getString("my_field");
} else {
//no results!
someField = null;
}
Alternatively, if you were looking for multiple results you can loop over #next
while (set.next()) {
//just one value out of many
String myField = set.getString("my_field");
}
In this use-case it's alright to check if the row exists, but I would personally check against something like user permissions or somesuch. If you relied on code like this for something sensitive you might expose something you don't want to.
Overall, I would work a little more on your logical structure for the code, and maybe go over some of the basics for Java and common coding standards for it (Google and Oracle have good guides for this).
Firstly, your class name initSql should have Capitalized first letter to follow conventions.
Secondly, you should either create an instance/object of InitSql and then call the method init() on that object or make the init() method static.
initSql.init() isn't static, which is not a problem of MariaDB and its connection from Java :) To fix this error you can add static to the mentioned method. But: As there are multiple errors in your code (e.g. assigning the result of a void method to a variable), it will not work then either..
I have a basic Java application (with a GUI) that uses a linked list to add/remove/modify Customer objects and I want to store them in a database (Oracle DB express to be exact)?
As I understand it, I have to create a table with some tool, and the use that tool to auto-generate a Java class that would allow me to communicate with the DB. How far off am I with this?
Just to make your question clear, What tool have you used to generate your java code?
I recommend you to avoid using code generation tool in case you want to learn in and out of Java.Here is an example of how you can connect your SWING application with Oracle DB,MySQL,Derby and many more other databases.
Connection con;
Statement smt;
ResultSet rs;
String user="databaseuser";
String pass="password";
String path="jdbc:oracle:thin:#localhost:1521:Sampledb"; //put db url here
try{
con=DriverManager.getConnection(path, user, pass);
smt=con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_UPDATABLE);
String SQL="SELECT *FROM Registered_users_tb "; //Your Query here
rs=smt.executeQuery(SQL);
rs.moveToInsertRow();
//First param is db column name,second param is variable name
rs.updateString("USERNAME", username);
rs.updateString("FNAME", fname);
rs.updateString("MNAME", mname);
rs.updateString("LNAME", lname);
rs.updateString("GENDER", gender);
rs.updateString("DEPARTMENT", dept);
rs.insertRow();
rs.close();
smt.close();
}
catch(SQLException err){
JOptionPane.showMessageDialog(Classname.this,err.getMessage());
}
For creating a complete new database, oracle provide a gui tool called DBCA. I found a couple of links to use this tool: Link 1 and Link 2
This tutorial teaches how to access an Oracle database. For accessing such an database you need additional drivers found here. Here an short example how to access such a database:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;
class DatabaseAccess
{
public static void main(String [] args)
{
Connection connection = null;
try
{
Class.forName("oracle.jdbc.OracleDriver");
String dbPath = "jdbc:oracle:thin:#localhost:1521:myDatabase";
String username = "user";
String password = "password";
connection = DriverManager.getConnection(dbPath, username, password);
if(connection != null)
{
System.out.println("Connected with database");
Statement statement = connection.createStatement();
ResultSet results = statementt.executeQuery("SELECT * FROM myTable");
while(result.next())
{
System.out.println(result.getString("myString"));
}
}
catch(ClassNotFoundException | SQLException exc)
{
exc.printStackTrace();
}
finally
{
try
{
connection.close();
}
catch(SqlException exc)
{
exc.printStackTrace();
}
}
}
}
For an more advanced example visit the given link.
So I just finished learning JDBC this weekend and have successfully transferred my code from the main method into an MVC app. The purpose of this application is to hold a roster of players and display a users credentials if requested. The program works great and when I request a url like...
http://localhost:8084/gmustudent/players?id=1
I get the correct output for that player! The problem is I am performing the database connection within my PlayersDAO class and I assume that this is not the "best" way to do this. So I have two questions.
Is there a way to perform the database connection within the web.xml
file or some other file so that when the server is initially started it will
immediately perform the connection to the database and be ready to
query when asked?
And is this actually a better alternative to having the connection in the DAO or would this have unforeseen negative drawbacks. AKA would a constant connection to my database be exactly what I do not want?
Any comments or links would be greatly appreciated. And I'll share the code I currently have for my DAO class so that you can see what I have so far. Thank you all!
package com.jdbc.test;
import java.sql.SQLException;
import java.sql.Connection;
import java.sql.Statement;
import java.sql.ResultSet;
import java.sql.DriverManager;
public class PlayersDAO
{
public static Players viewPlayer(int id) throws SQLException
{
Connection connection = null;
Statement statement = null;
ResultSet resultSet = null;
Players playerObject = null;
try
{
String url = "jdbc:mysql://localhost:3306/gmustudent";
String username = "root";
String password = "root";
try
{
Class.forName("com.mysql.jdbc.Driver");
}
catch(ClassNotFoundException error)
{
System.out.println("Error: " + error.getMessage());
}
connection = DriverManager.getConnection(url, username, password);
statement = connection.createStatement();
resultSet = statement.executeQuery("SELECT * FROM players WHERE id = " + id);
if(resultSet.next())
playerObject = new Players(resultSet.getLong("id"), resultSet.getString("name"), resultSet.getString("position"), resultSet.getString("height"), resultSet.getString("year"), resultSet.getString("hometown"), resultSet.getString("highschool"), resultSet.getString("headshot"));
}
finally
{
if (connection != null) try{connection.close();} catch(SQLException ignore) {}
if (statement != null) try{statement.close();} catch(SQLException ignore) {}
if (resultSet != null) try{resultSet.close();} catch(SQLException ignore) {}
}
return playerObject;
}
}
You can create database connection in web.xml file by using resource. I hope this tutorial will help you.
http://viralpatel.net/blogs/database-connection-pooling-tomcat-eclipse-db/
You can use JDBC Connection Pooling.It can provide significant benefits in terms of application performance, concurrency and scalability.
IMHO, its always a good approach to hide the instantiation details of any resources. You can use factory method to do this. The advantage of this approach is that you can always change the way to manage the resources - e.g. You can have one instance of JDBCConnection per DAO or you can have connection pool. Any time you can provide your development specific db connection, test specific db connection or production db connection. All these details you can hide doing such approach.
I have written a connection code with oracle. But still I am getting errors. I'll type the code of mine here.
import java.sql.*;
public class SimpleOraJava {
public static void main(String[] args) throws SQLException, ClassNotFoundException {
// TODO Auto-generated method stub
DriverManager.registerDriver(new Oracle.jdbc.driver.OracleDriver());
String serverName="10.20.228.67";
String user="root";
String password="root";
String SID="abc";
String URL="jdbc:oracle:thin:#"+serverName+":"+1520+":"+SID;
Connection conn=DriverManager.getConnection(URL, user, password);
String SQL="Select employeename from employee";
Statement stat=conn.createStatement();
ResultSet rs=stat.executeQuery(SQL);
while (rs.next()){
System.out.println(rs.getInt(1));
}
stat.close();
conn.close();
}
}
It shows error in this line:
DriverManager.registerDriver(new Oracle.jdbc.driver.OracleDriver());
The error is on the word Oracle. It is asking me to create class in package oracle.jdbc.driver
Please somebody help!
Okay, assuming that class-paths are set up, and the appropriate .jar files are in the correct directories, the first thing that jumps out is I believe you need to import the package into your class. There should be a import oracle.jdbc.driver.*; line under the import java.sql.*; line also the DriverManager call should be
DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
with the lowercase o, it's capitalized in your code.
Another thing might be, the version of the Oracle JDBC, and Oracle client you're using. According to this OTN Discussion post Oracle JDBC 10.2 is the last release to support the package oracle.jdbc.driver.
So basically according to the metalink page if you're using a JDBC 10.2 or older client, something like this will work:
import java.sql.*;
import oracle.jdbc.driver.*;
public class myjdbcapp
{
public static void main(String[] args) throws SQLException
{
DriverManager.registerDriver(new oracle.jdbc.OracleDriver());
String url = "jdbc:oracle:thin:#server:port:orcl";
String userName = "scott";
String password = "tiger";
Connection conn = DriverManager.getConnection (url, userName, password);
OracleCallableStatement myprocst = (OracleCallableStatement)
conn.prepareCall ("begin myproc(?); end;");
// ...
}
}
Clients newer than JDBC 10.2 will need to change import oracle.jdbc.driver.; to import oracle.jdbc.;
DriverManager.registerDriver(new Oracle.jdbc.driver.OracleDriver());
The package is oracle.jdbc.driver with a lowercase o.