Using database mysql in Java - java

I have started trying out some stuff so that I can use mysql database together with Java. First of all I have some questions about it.
I have used mysql a lot with PHP development but never with Java. Can I use the MySQL that MAMP brings or do I have to install it stand alone or something?
and second.. I have created this code with the help of a tutorial but the only output I get is
com.mysql.jdbc.Driver
The code that I have used for this you can find below:
package Databases;
import java.sql.*;
public class MysqlConnect{
/* These variable values are used to setup
the Connection object */
static final String URL = "jdbc:mysql://localhost:3306/test";
static final String USER = "root";
static final String PASSWORD = "root";
static final String DRIVER = "com.mysql.jdbc.Driver";
public Connection getConnection() throws SQLException {
Connection con = null;
try {
Class.forName(DRIVER);
con = DriverManager.getConnection(URL, USER, PASSWORD);
}
catch(ClassNotFoundException e) {
System.out.println(e.getMessage());
System.exit(-1);
}
return con;
}
public void getEmployees() {
ResultSet rs = null;
try {
Statement s = getConnection().createStatement();
rs = s.executeQuery("SELECT id, name, job_id, location FROM person");
System.out.format("%3s %-15s %-7s %-7s%n",
"ID", "NAME", "JOB ID",
"LOCATION");
System.out.format("%3s %15s %7s %7s%n",
"---", "---------------",
"-------", "--------");
while(rs.next()) {
long id = rs.getLong("id");
String name = rs.getString("name");
long job = rs.getLong("job_id");
String location = rs.getString("location");
System.out.format("%-3d %-15s %7d %5s%n",
id, name, job, location);
}
}
catch(SQLException e) {
System.out.println(e.getMessage());
System.exit(-1);
}
}
}

It's coming from the following block:
catch(ClassNotFoundException e) {
System.out.println(e.getMessage());
System.exit(-1);
}
That's a pretty poor way of handling exceptions. You're just printing the exception message. You have no clue what's going on. Rather just throw it (which will end up with a nice stacktrace), or print a more descriptive message along alone the exception message, e.g.
catch(ClassNotFoundException e) {
System.out.println("JDBC driver class not found in runtime classpath: " + e.getMessage());
System.exit(-1);
}
How to fix the particular exception is in turn actually a second question (with a pretty obvious answer: just put JAR file containing JDBC driver class in runtime classpath), but ala, you may find this mini-tutorial helpful then: Connect Java to a MySQL database.
Unrelated to the concrete problem, I'm not sure which tutorial you're reading there, but I'd take it with a grain of salt. Apart from poor exception handling, it's also leaking DB resources in getEmployees() method by never closing the result set, statement and connection. This is absolutely not a good practice either. How to do it is also already covered in the aforelinked mini-tutorial. See further also: How often should Connection, Statement and ResultSet be closed in JDBC?

Yes, you need to install MySQL server locally or remotely.
The code will be usable if you also downloaded jdbc Driver jar from MySQL download pages. and you configured your MySQL instance with the proper username and password.

Related

ORA-01017 error when attempting to connect to Oracle XE from servlet

I'm trying to write a servlet application for learning purposes that connects to an Oracle database, queries some data and then prints it to the browser. Simple!
However, I'm experiencing an ORA-01017: invalid username/password when attempting to connect to a locally installed and running version of Oracle XE (19c). For the sake of testing the connection, I'm connection with the system user. Here's my code:
// http://localhost:8080/demo/
public class DemoServ extends HttpServlet {
public void doGet(HttpServletRequest req,HttpServletResponse res)
throws ServletException,IOException {
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con = DriverManager.getConnection("jdbc:oracle:thin:#localhost:1523:xe", "system", "SYSTEM");
con.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
The user that I'm using absolutely does exist, and I can connect using SQL Developer without issue.
I would be willing to put this down to my own ignorance of Java, but if I run the following code independently of any servlet, I can connect and execute the sample query!
public class DataReader {
public static void main (String [] args) {
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con = DriverManager.getConnection("jdbc:oracle:thin:#localhost:1523:xe", "system", "SYSTEM");
Statement statement = con.createStatement();
ResultSet rs = statement.executeQuery("SELECT count(*) num FROM dual");
if (rs.next()) {
int i = rs.getInt("num"); // get first column returned
System.out.println("number: " + i);
}
rs.close();
statement.close();
con.close();
}
catch (Exception e) {
System.out.println(e);
}
}
}
I've been searching Google for solutions to this, but I have been unable to find a solution, so here I am.
I'm working on Windows 10, using Java 1.8 and Oracle 19c XE.
Any help would be great. Thanks
Okay, I finally go this to work, but I cannot explain why.
Oracle 19c is case sensitive, which I knew. I attempted to disable this, but as it's a depreciated feature, this seemed expeditious. I altered the password for the system user to be "system", and I can connect successfully. "SYSTEM" as a password continues to fail.
What strikes me as odd about this is that I'm sure that I tried to use the "system" (lowercase) password in the past. :(
Anyway, I probably was doing something daft, but at least I'm got over the hump. Phew!
Thank you to everyone!!

H2 Database, problems getting data from tables

I'm creating a JavaFX application, I've connected to the database fine. However when i look to get data from the tables i get the error
org.h2.jdbc.JdbcSQLException: Table "LECTURE" not found; SQL
statement: SELECT NAME FROM Lecture [42102-192]
and I'm 100% sure i'm connected to the database and the table is definitely there, any suggestions on why this is?
hear is my connection code and the code i am running just so you can see
public class ConnectionFactory {
//static reference to itself
private static ConnectionFactory instance = new ConnectionFactory();
public static final String URL = "jdbc:h2:file:~/db\\.";
public static final String USER = "notepad";
public static final String PASSWORD = "password";
public static final String DRIVER_CLASS = "org.h2.Driver";
//private constructor
private ConnectionFactory() {
try {
Class.forName(DRIVER_CLASS);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
private Connection createConnection() {
Connection connection = null;
try {
connection = DriverManager.getConnection(URL, USER, PASSWORD);
} catch (SQLException e) {
System.out.println("ERROR: Unable to Connect to Database.");
}
return connection;
}
public static Connection getConnection() {
return instance.createConnection();
}
}
And the query being run
private void onLoadYearSelect() {
try {
Connection con = ConnectionFactory.getConnection();
Statement stat = con.createStatement();
String query = "SELECT NAME FROM Lecture";
ResultSet years = stat.executeQuery(query);
while(years.next()){
yearSelect.setValue(years.getString("NAME"));
System.out.println(years.getString("NAME"));
}
} catch (SQLException e) {
e.printStackTrace();
}
}
public void initialize(){
onLoadYearSelect();
}
If it says the table doesn't exist, then it really doesn't exist.
Most likely, you are not actually connecting to the correct database. In fact, by default, if the connection string points to a non-existent database, it just creates an empty database on the fly, which would explain your error.
It's probably too late now (because there is probably a 2nd database created already somewhere), but to avoid this confusion, it's not a bad idea to include IFEXISTS=TRUE in the connection string so that it fails if the database doesn't exist, rather than creating an empty one that will mask the true problem.
public static final String URL = "jdbc:h2:file:~/db\\.;IFEXISTS=TRUE";
However, one thing you can still try to debug the problem, is to add IFEXISTS=TRUE to the connection string. Then move or rename the database you think it should be connecting to so as to make the connection string invalid. Basically, force it to fail. If the code still connects to the database successfully, then you'll know the connection string is not pointing to the location you think it is.

how to take database as parameter to connect to mysql database server

import java.sql.*;
class ConnectSql
{
static Connection cont(String db)throws Exception
{
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/"+db+","root","xyz" );
return(con);
}
}
I am facing a problem in compiling this function and this 7th line is i suppose a problem is there an syntax error.If so please tell me.Here i want to take the name of database as parameter received from calling function.When i gave the exact name of database instead of parameter it worked,but not after i passed parameter in connection line.
it should be
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/"+db,"root","xyz" );
problem is
"+db+"
you have extra " mark
Connection con=null;
String DB_URL = "jdbc:mysql://localhost:3306/";
String USER = "abc";//db user name
String PASS = "abc";//db password
public synchronized Connection getConnection(String dbname)
{
try
{
Class.forName("com.mysql.jdbc.Driver");//loading mysql driver
con = DriverManager.getConnection(DB_URL+dbname,USER,PASS);//connecting to mysql
}
catch(Exception e)
{
e.printStackTrace();
}
return con;
}

Connection Closed even when the connection is closed below the code

I have a basic code snippet below but it is not working.What may be the problem with it.
public List<String> getStores() throws SQLException{
List<String> store_id=new ArrayList<>();
String query="select distinct(store_id) from stores";
Connection con=ConnectDatabase.getDb2ConObj();
Statement stmt=con.createStatement();
java.sql.ResultSet rsResultSet=stmt.executeQuery(query);
while(rsResultSet.next()){
store_id.add(rsResultSet.getString(1));
}
con.close();
return store_id;
}
It is throwing the below exception
com.mysql.jdbc.exceptions.MySQLNonTransientConnectionException: No operations allowed after connection closed.
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:888)
at com.mysql.jdbc.Connection.checkClosed(Connection.java:1931)
at com.mysql.jdbc.Connection.createStatement(Connection.java:3087)
at com.mysql.jdbc.Connection.createStatement(Connection.java:3069)
at com.dao.StoreDao.getStores(StoreDao.java:52)
at org.apache.jsp.adminViewAllStore_jsp._jspService(adminViewAllStore_jsp.java:119)
The code for ConnectDatabse is
public class ConnectDatabase {
static Connection con=null;
static String connectionString="jdbc:mysql://localhost:3306/ayurveda";
static String username="root";
static String password="";
public static Connection getDb2ConObj(){
if(con==null){
try{
Class.forName("com.mysql.jdbc.Driver");
con=DriverManager.getConnection(connectionString,username,password);
}
catch(ClassNotFoundException | SQLException e)
{
System.out.println("Connect initialized with error"+e.getMessage());
e.printStackTrace();
}
}
return con;
}
I cannot understand the reason for the same.What may be the problem.Since I am closing the connection after I am done with it.
It worked after I enclosed it in a try catch finally block.Changed the code as given below
public List<String> getStores() throws SQLException{
List<String> store_id=new ArrayList<>();
Connection con=ConnectDatabase.getDb2ConObj();
try{
String query="select distinct(store_id) from stores";
Statement stmt=con.createStatement();
java.sql.ResultSet rsResultSet=stmt.executeQuery(query);
while(rsResultSet.next()){
store_id.add(rsResultSet.getString(1));
}
}catch(Exception e){
}finally{
con.close();
}
return store_id;
}
Thanks.
You can use this type of code...for solving your problem
public void actionPerformed(ActionEvent ae)
{
String u=t1.getText();
String p=t2.getText();
if(ae.getSource()==b1)
{
try{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con=DriverManager.getConnection("jdbc:odbc:newdsn");
String stp="SELECT * FROM reg";
Statement sa=con.createStatement();
rs=sa.executeQuery(stp);
while(rs.next())
{
String du=rs.getString(2);
String dp=rs.getString(3);
if(du.equals(u)&&dp.equals(p))
{
a=0;
break;
}else{ a=1;}
}
if(a==0){
JOptionPane.showMessageDialog(this,"LOGIN PAGE","Login is successful",1);
}
if(a==1){
JOptionPane.showMessageDialog(this,"LOGIN PAGE","Login is not successful",1);
}}
catch(Exception e){}
}}
if even the it is throwing exception then you check the system 32 bit or 64 bit..you should try if 64bit then please make your dsn in 32 bit and anduse ms access 2002-2003 version
then you get tour solution .....thank u
Use Java 7 -The try-with-resources Statement
According to the oracle documentation, you can combine a try-with-resources block with a regular try block
The typical Java application manipulates several types of resources such as files, streams, sockets, and database connections. Such resources must be handled with great care, because they acquire system resources for their operations. Thus, you need to ensure that they get freed even in case of errors.
Indeed, incorrect resource management is a common source of failures in production applications, with the usual pitfalls being database connections and file descriptors remaining opened after an exception has occurred somewhere else in the code. This leads to application servers being frequently restarted when resource exhaustion occurs, because operating systems and server applications generally have an upper-bound limit for resources.
sample code:
try(Connection con = getConnection()) {
...
}
Read more Java 7 Automatic Resource Management JDBC
Close Statement and ResultSet as well.
Don't load driver class every time when connection is needed. Just load it once in static initialization block.
static {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
I suggest you to use JNDI and DataSource to keep username and password outside the Java code to make it more manageable. Keep the database configuration in a separate xml/properties file instead of hard-coding in Java file.
See Java Tutorial on Connecting with DataSource Objects
I have already posted a nice ConnectionUtil class to manage all the connections in a single class for whole application.

How can I connect to a MySQL web server with Java?

Alright, so here's a little bit of background:
I am currently trying to develop a referral application. There is a link on our website where a user can refer their friends to our game server (Minecraft). It will input the referrer's information into a database (hosted on my website) and send a link to the "friend". The friend clicks on the link and enters their information (which also gets stored in the database). All of this is working great! (Yay!) So, now for the Java Plugin!
What is supposed to happen...
I have an Event Listener that will fire whenever a user logs into the game. Essentially, it would check the data base for the user's info, and if the user meets the criteria, then it will award them with their extra referral goodies.
What I am trying to do right now...
Right now, I am essentially trying to just get it to connect and display the id of the row, and the ref_id (Referral ID) when the plugin is enabled. But, I'm getting the following 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.
So, without further ado, here is my singular Java document. Of course, that is not the real username and login information to my database. ;) But I'm hoping someone here can tell me what's wrong, because I'm so lost, right now.
package com.arithia.plugins;
import java.sql.*;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerLoginEvent;
import org.bukkit.plugin.java.JavaPlugin;
public class ArithiaReferrals extends JavaPlugin implements Listener {
// JDBC driver name and database URL
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://66.147.244.122:3306/graphja6_referrals";
// Database credentials
static final String USER = "fake_username";
static final String PASS = "fake_password";
#Override
public void onEnable() {
Connection conn = null;
Statement stmt = null;
try {
// STEP 2: Register JDBC driver
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// STEP 3: Open a connection
getLogger().info("Connecting to database...");
conn = DriverManager.getConnection(DB_URL, USER, PASS);
// STEP 4: Execute a query
getLogger().info("Creating statement...");
stmt = conn.createStatement();
String sql;
sql = "SELECT id, ref_id FROM referred_users";
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 ref_id = rs.getInt("ref_id");
// Display values
getLogger().info("ID: " + id);
getLogger().info("Referral ID: " + ref_id);
}
// STEP 6: Clean-up environment
rs.close();
stmt.close();
conn.close();
}catch(SQLException se) {
// Handle errors for JDBC
se.printStackTrace();
}finally{
// finally block used to close resources
try{
if(stmt!=null)
stmt.close();
}catch(SQLException se2){
} // nothing we can do
try {
if(conn!=null)
conn.close();
}catch(SQLException se){
se.printStackTrace();
} // End Finally try
} // end try
getLogger().info("Goodbye!");
getLogger().info("The [Arithia Referrals] plugin was enabled!");
}
#Override
public void onDisable() {
getLogger().info("The [Arithia Referrals] plugin was disabled!");
}
#EventHandler
public void onPlayerLogin(PlayerLoginEvent e) {
// "Check database for player..."
}
}
Other Information...
Database Name: graphja6_referrals
Database Table: referred_users
Note: I am not entirely sure that the DB_URL is correct... 66.147.244.122 is the correct IP, but I'm not entirely sure about the port or anything else, so if someone could verify that's correct, I'd be appreciative.
Thank you very much for your help.
Okay, so I'm just an idiot.
For anyone else getting this error, you need to whitelist the IP of the remote connection for this to work. It is a firewall thing, and depending on who you host with, there's probably a "Remote MySQL" option in the cPanel. Add the IP to the remote client that is trying to access the database, so it will be whitelisted.
Thank you to everyone who tried to help. <3

Categories

Resources