I have been trying this for a few hours now but with no success. I downloaded the JDBC driver and it shows that it is one of my referenced libraries under my Package Explorer in Eclipse but every time I try to run my code I get errors. My database is fine as I can change it and view it from the MySQL Command Line Client.
I actually followed a guides directions on how to do it, only replacing the information from their database to information about mine.
import java.sql.*;
public class FirstExample {
//JDBC Driver Name and Database URL
final static String JDBC_DRIVER = "com.mysql.jdbc.Driver";
final static String DB_URL = "jdbc:mysql://localhost/test_database";
//Database Credentials
static final String USER = "user_one";
static final String PASS = "User_one_password";
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
try {
//Register JDBC Driver
Class.forName("com.mysql.jdbc.Driver");
//Open a Connection
System.out.println("Connecting to the Database...");
conn = DriverManager.getConnection(DB_URL, USER, PASS);
//Execute a Query
System.out.println("Creating Statement...");
stmt = conn.createStatement();
String sql;
sql = "SELECT * FROM user";
ResultSet rs = stmt.executeQuery(sql);
//Extract Data from Result Set
while (rs.next()) {
//Retrieve by Column Name
int id = rs.getInt("id");
String first = rs.getString("name");
//Display Values
System.out.print("ID: " + id);
System.out.println("Name: " + first);
}
//Clean Up Environment
rs.close();
stmt.close();
conn.close();
} catch (SQLException se) {
//Handle Errors For JDBC
se.printStackTrace();
} catch (Exception e) {
//Handle Errors for Class.forName
e.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 (Exception se) {
se.printStackTrace();
}//End Finally Try
}//End Try
System.out.println("Goodbye!");
}//End Main
}//End First Example
Here is the error I get http://pastebin.com/hLSxV3aq
Related
I've got a mysql question within java. I've got a mysql database with different tables. I currently got a database called 'litebans' and a table called 'litebans_mutes'.
Within that table there is a row called reason and under that reason (let's say what's within reason) there's a string called 'This is a test' and 'sorry'; how would I get the string 'This is a test' and 'sorry' associated with the same 'uuid' row in java? Here is a picture explaining more:
Here is an image explaining the sql format
Additionally, i've currently initialized all variables and such in java, i currently have this code:
http://hastebin.com/odumaqazok.java (Main class; using it for a minecraft plugin)
The below code is the MySQL class; api used to connect and execute stuff.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import net.octopusmc.punish.Core;
public class MySQL {
public static Connection openConnection() {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e1) {
System.err.println(e1);
e1.printStackTrace();
}
try {
Connection conn = DriverManager.getConnection("jdbc:mysql://" + Core.host + ":" + Core.port + "/" + Core.database, Core.user, Core.pass);
System.out.println("Currently connected to the database.");
return conn;
} catch (SQLException e) {
System.out.println("An error has occured while connecting to the database");
System.err.println(e);
e.printStackTrace();
}
return null;
}
public static void Update(String qry) {
try {
Statement stmt = Core.SQLConn.createStatement();
stmt.executeUpdate(qry);
stmt.close();
} catch (Exception ex) {
openConnection();
System.err.println(ex);
}
}
public static Connection getConnection() {
return Core.SQLConn;
}
public static ResultSet Query(String qry) {
ResultSet rs = null;
try {
Statement stmt = Core.SQLConn.createStatement();
rs = stmt.executeQuery(qry);
} catch (Exception ex) {
openConnection();
System.err.println(ex);
}
return rs;
}
}
An example using that api above is shown below:
try {
ResultSet rs = MySQL.Query("QUERY GOES HERE");
while (rs.next()) {
//do stuff
}
} catch (Exception err) {
System.err.println(err);
err.printStackTrace();
}
tl;dr: I want to get the two fields called 'reason' with the give 'uuid' string field.
First , make sure that your using the jdbc mysql driver to connect to the database
Defile a class where you could write the required connection and create statement code.
For example
class ConnectorAndSQLStatement {
ResultSet rs = null;
public Statement st = null;
public Connection conn = null;
public connect() {
try {
final String driver = "com.mysql.jdbc.Driver";
final String db_url = "jdbc:mysql://localhost:3306/your_db_name";
Class.forName(driver);//Loading jdbc Driver
conn = DriverManager.getConnection(db_url, "username", "password");
st = conn.createStatement();
rs = st.executeQuery("Select what_you_want from your_table_name");
while (rs.next()) {
String whatever = rs.getInt("whatever ");
System.out.print(whatever);
}
} catch (SQLException se) {
se.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
Just call this function and the magic :D
Hope it is helpful
I am pretty new to Java so I'm working on a project to develop my knowledge with databases and Java.
I have figured out how to add queries into the database but now I'm getting errors when trying to print them out.
Assume I already have everything that's necessary imported in such as the scanner and sql statements
Here is my connection class which is named MainClass:
public static Connection getConnection() throws Exception {
String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost:3306/testTable";
String username = "placeholder";
String password = "placeholder";
Class.forName(driver);
Connection conn = Driver Manager.getConnection(url, username, password);
return conn;
}
Now in a different class if the user types !lookup and a word I want the definition of that word to be retrieved from the table whose name is dictionary and columns are word, definition:
String userSearch = user_input.next();
String[] userSearchSplit = userSearch.split(" ", 3);
if (userSearchSplit[0].equals("!lookup")) {
try {
conn = MainClass.getConnection();
String query = "select definition from dictionary where word=" + userSearchSplit[1];
ResultSet result = pstmt.executeQuery(query);
while (result.next()) {
String definition = result.getString("definition");
System.out.println(definition);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
pstmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
At the end of all this when I try to look up a word I put in the table before running I get:
java.lang.NullPointerException
Check if your user_input is null?
I am assuming your code:
ResultSet result = pstmt.executeQuery(query);
as
Statement pstmt = conn.createStatement();
ResultSet result = pstmt.executeQuery(query);
Or it could be that you have not initialized the pstmt properly
I am trying to validate a database (phpMyadmin) using Username and Password. I need to search in all the tables (25 tables in my database) for checking if the given username and password are present (Authentication) or not. Can anyone provide the query to search entire table using the given username and password?
Below is my code
public class Dbclass {
/**
* #param args
*/
Connection conn = null;
Statement statement = null;
ResultSet resultSet = null;
ResultSetMetaData metaData = null;
String DB_URL="com.mysql.jdbc.Driver";
String USER="java";
String PASS="redhat";
String username;
String password;
ResultSet rs;
public ResultSet dbConnection(String query)
{
//STEP 2: Register JDBC driver
try {
Class.forName("com.mysql.jdbc.Driver");
//STEP 3: Open a connection
System.out.println("Connecting to database...");
try {
conn = DriverManager.getConnection(DB_URL,USER,PASS);
//STEP 4: Execute a query
System.out.println("Creating statement...");
Statement stmt = conn.createStatement();
//sql = "SELECT username,password FROM Employees";
rs = stmt.executeQuery(query);
while(rs.next()){
//Retrieve by column name
username = rs.getString("user_name");
password = rs.getString("password");
//Display values
System.out.print("User_name: " + username);
System.out.print(",Password: " + password);
}
Authentication obj=new Authentication();
obj.userLogin(username,password);
//STEP 6: Clean-up environment
//rs.close();
//return rs;
stmt.close();
conn.close();
} catch (SQLException e) {
//TODO Auto-generated catch block
e.printStackTrace();
}
} catch (ClassNotFoundException es) {
//TODO Auto-generated catch block
es.printStackTrace();
}
finally{
//finally block used to close resources
try{
if(conn!=null){
conn.close();
}
if (rs != null) {
rs.close();
}
}catch(SQLException se){
se.printStackTrace();
}//end finally try
}//end try
return rs;
}
}
I guess you're looking for a where clause. Something like below.
SELECT username,password FROM Employees where username='usernm' and password='pwd'
If required, you can add UNION to merge more such queries, but not recommended due to performance issues.
I am using Java and MySQL.
I have two sql statement in two separate function, one create database, another create tables.
I try to write try & catch exception block in each function, it works, like code below.
public class j_sql1 {
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost";
static final String DB_URL2 = "jdbc:mysql://localhost/zxc";
static final String USER = "root";
static final String PASS = "";
static Connection conn = null;
static Statement stmt = null;
public static void create_db()
{
conn = null;
stmt = null;
try{
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(DB_URL, USER, PASS);
stmt = conn.createStatement();
String sql = "CREATE DATABASE zxc";
stmt.executeUpdate(sql);
stmt.close();
conn.close();
}
catch(SQLException se){
se.printStackTrace();
}
catch(Exception e){
e.printStackTrace();
}
finally
{
try{
if(stmt!=null)
stmt.close();
}
catch(SQLException se2){}
try{
if(conn!=null)
conn.close();
}
catch(SQLException se){
se.printStackTrace();
}
}
}
public static void create_tables ()
{
conn = null;
stmt = null;
try{
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(DB_URL2, USER, PASS);
stmt = conn.createStatement();
String sql = "CREATE TABLE ABC("+
"abc_ID int NOT NULL AUTO_INCREMENT,"+
"abc_Name varchar(50),"+
"PRIMARY KEY (abc_ID))";
stmt.executeUpdate(sql);
stmt.close();
conn.close();
}
catch(SQLException se){
se.printStackTrace();
}
catch(Exception e){
e.printStackTrace();
}
finally
{
try{
if(stmt!=null)
stmt.close();
}
catch(SQLException se2)
{}
try{
if(conn!=null)
conn.close();
}
catch(SQLException se){
se.printStackTrace();
}
}
}
public static void main(String[] args)
{
create_db();
create_tables();
}
}
But what if only one catch exception block in the main for my two try blocks in the two functions something like the code below, possible?
public class j_sql1 {
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost";
static final String DB_URL2 = "jdbc:mysql://localhost/zxc";
static final String USER = "root";
static final String PASS = "";
static Connection conn = null;
static Statement stmt = null;
public static void create_db()
{
conn = null;
stmt = null;
try{
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(DB_URL, USER, PASS);
stmt = conn.createStatement();
String sql = "CREATE DATABASE zxc";
stmt.executeUpdate(sql);
stmt.close();
conn.close();
}
}
public static void create_tables ()
{
conn = null;
stmt = null;
try{
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(DB_URL2, USER, PASS);
stmt = conn.createStatement();
String sql = "CREATE TABLE ABC("+
"abc_ID int NOT NULL AUTO_INCREMENT,"+
"abc_Name varchar(50),"+
"PRIMARY KEY (abc_ID))";
stmt.executeUpdate(sql);
stmt.close();
conn.close();
}
}
public static void main(String[] args)
{
try
{
create_db();
create_tables();
}
catch(SQLException se){
se.printStackTrace();
}
catch(Exception e){
e.printStackTrace();
}
finally
{
try{
if(stmt!=null)
stmt.close();
}
catch(SQLException se2)
{}
try{
if(conn!=null)
conn.close();
}
catch(SQLException se){
se.printStackTrace();
}
}
}
}
And why the variable like Connection, Statement and the functions have to be declared to static?
Thank You.
In the static main, there is no object instance of the class j_sql1. Hence only static fields may be read.
You should do
Naming convention the same as 99.9 % of java users:
class JSql1
void createDB()
void createTables()
Instantiate an object, and call functions on it:
... main(...) {
JSql1 app = new JSql1();
try {
app.openConnection();
app.createDB();
app.createTables():
} catch (SQLException e) {
Logger.getLogger(JSql1.class.getName()).log(Level.FATAL, "...", e);
} finally {
app.close();
}
When createDB fails, there is no need to continue, hence createDB should throw the
exception.
Also the functions are uaseful inside a single connection, so create the connection
separately.
Design decision, but at least for statements declare all as locally as possible
Especially try-with-resource for automatically closing helps here
class JSql1;
Connection conn;
void createTables() throws SQLException {
try (Statement stmt = conn.createStatement()) {
String sql = "CREATE TABLE ABC(" +
"abc_ID int NOT NULL AUTO_INCREMENT," +
"abc_Name varchar(50)," +
"PRIMARY KEY (abc_ID))";
stmt.executeUpdate(sql);
}
}
I checked everything like username, password, db_url, table name, etc but still I get this output---connecting to database
creating statement
java.lang.NullPointerException
here is my code, (I'm using eclipse Kepler EE and MySQL 5.6.17.0)
import java.sql.*;
public class Demo {
static final String JDBC_DRIVER="com.mysql.jdbc.Driver";
static final String DB_URL="jdbc:mysql://localhost/sample";
static final String USER="root" ;
static final String PASS="root";
public static void main(String[] args)
{
Connection conn=null;
Statement stmt=null;
try
{
Class.forName("com.mysql.jdbc.Driver");
System.out.println("connecting to database");
conn=DriverManager.getConnection(DB_URL, USER, PASS);
System.out.println("creating statement");
String sql="select * from sample";
ResultSet rs=stmt.executeQuery(sql);
while(rs.next())
{
int eid=rs.getInt("id");
String ename=rs.getString("name");
System.out.print(eid+"\t");
System.out.print(ename);
System.out.println("");
}
rs.close();
stmt.close();
conn.close();
}catch(Exception e)
{
System.out.println(e);
}
finally
{
try
{
if(stmt!=null)
{
stmt.close();
}
}catch(Exception e)
{
System.out.println(e);
}
try
{
if(conn!=null)
{
conn.close();
}
}catch(Exception e)
{
System.out.println(e);
}
}
}
}
I don't think your statement is set. It is always null.
I think you should use this:
stmt = conn.createStatement( );
You didnt create stmt object
stmt = conn.createStatement( );
You have to add above line before this line ResultSet rs=stmt.executeQuery(sql);
You are executing query on a null object.
So getting NPE
You set Statement stmt=null; and you never initialize it later.