How to get a String from a field - java

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

Related

SQLException: ERROR: syntax error at or near "\"

I want to get a list of tables in ma database to String. I have connect with database, but when I try use Postgres "\dt" function, getTables() throws org.postgresql.util.PSQLException: ERROR: syntax error at or near "\".
What is the problem? A simple backslash is reported as an error by
JDK (treats \dt as regex).
import java.sql.*;
import java.util.ArrayList;
public class DataConnect {
Statement statement = null;
Connection connection = null;
DataConnect() {
try {
Class.forName("org.postgresql.Driver");
connection = DriverManager.getConnection("jdbc:postgresql://localhost:5432/postgres", "", "");
statement = connection.createStatement();
} catch (ClassNotFoundException e) {
e.printStackTrace();
System.out.append("Driver is missing");
end();
} catch (SQLException e) {
e.printStackTrace();
System.out.append("Wrong order");
end();
}
}
ArrayList<String> getTables() {
ArrayList tables = new ArrayList();
try {
ResultSet rs = statement.executeQuery("\\dt");
while (rs.next()) {
String databaseName = rs.getString("Name");
}
return tables;
} catch (Exception e) {
e.printStackTrace();
end();
return null;
}
}
}
\dt isn't valid SQL syntax - it's a psql meta-command. You can perform a similar functionality by querying the information schema:
ResultSet rs = statement.executeQuery("SELECT table_name FROM information_schema.tables");

How to return result set from method in jdbc connection

This is my connetion class. i need to return resultset to specific class. but i found resultset is closed in that class. i use connectio pooling in my connection.
i want to create general connection class that manages all operations for database in my application.
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
public class OpenTestConnection {
private DataSource dataSource=null;
private Connection connection=null;
private Statement statement=null;
public OpenTestConnection()
{
System.out.println("come in Openconnection....");
try {
// Get DataSource
Context initContext = new InitialContext();
Context envContext = (Context)initContext.lookup("java:/comp/env");
dataSource = (DataSource)envContext.lookup("jdbc/ietddb");
} catch (NamingException e) {
e.printStackTrace();
}
}
private Connection getConnection() throws SQLException {
return dataSource.getConnection();
}
public ResultSet selectfromtable(String sql)
{
System.out.println("come here....");
ResultSet resultSet = null;
try {
connection = getConnection();
statement = connection.createStatement();
resultSet = statement.executeQuery(sql);
} catch (SQLException e) {
e.printStackTrace();
}finally {
try { if(null!=resultSet)resultSet.close();} catch (SQLException e)
{e.printStackTrace();}
try { if(null!=statement)statement.close();} catch (SQLException e)
{e.printStackTrace();}
try { if(null!=connection)connection.close();} catch (SQLException e)
{e.printStackTrace();}
}
return resultSet;
}
}
Well Shree has answered your issue. You have closed the ResultSet before returning it.
However, to add to what you are trying to achieve.
1) surround your return dataSource.getConnection in try catch.
2) Create seperate query function and connection close function like below
protected Connection connection = null;
protected Statement statement = null;
protected PreparedStatement prepared = null;
// executeQuery
protected ResultSet execute(String sql) throws SQLException {
connection = getConnection();
statement = connection.createStatement();
return statement.executeQuery(sql);
}
//now have a close function
protected void commitAndClose() {
if (connection != null) {
try {
connection.commit();
} catch (SQLException ex) {
// your code for handling ex
} finally {
try {
resultSet.close(); //do not know why you are closing resultset
statement.close();
connection.close();
} catch (SQLException ex) {
LOGGER.log(Level.SEVERE, null, ex);
}
connection = null;
}
}
}
This will give you more flexibilty when your code expands.

java.sql.SQLException: Invalid handle

I'm trying to teach myself how to connect to a msaccess database in java.
I have set up a class to access the database as follows
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public abstract class AccessDBConnect2 {
public static Connection connect(){
String fileName = "C:/Users/Bridget/Documents/EmployeeSys.accdb";
Connection con = null;
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String url = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ="+fileName;
con = DriverManager.getConnection(url,"","");
} catch (Exception e) {
// Handle exceptions ...
System.out.println(e.toString());
System.out.println("A problem accessing the database");
e.printStackTrace();
} finally {
try { if(con!=null) {con.close();} } catch (Exception e) {}
}
return con;
}
public static void closeConnection(Connection conn){
try{
conn.close();
}catch (Exception e){
}
}
Then I have my code which is just trying to select everything from the table.
I have created the table in msAccess and the code seems to get through the connect method in the above code without any problems, indicating it is finding the database and accessing it somewhat. The problem happens when I call the prepareStatement using the connection, i.e. code line:
stm = conn.prepareStatement(sql);
The full code is:
import java.sql.*;
public class Program2{
public static void main(String[] args) {
try{
// Load the JDBC driver
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver").newInstance();
// Establishing db connection
Connection conn = AccessDBConnect.connect();
// Displaying all records from employee file
System.out.println("Display records of all employees");
display(conn);
// Closing the connection
AccessDBConnect.closeConnection(conn);
}catch (Exception e){
System.out.println("Error");
}
}
// Display details of all employees
public static void display(Connection conn){
PreparedStatement stm = null;
// SQL statement
String sql = "SELECT * FROM Employee";
ResultSet rs;
try {
stm = conn.prepareStatement(sql); // Prepare the SQL statement
rs = stm.executeQuery(); // Execture the SQL statement
// Navigate through the ResultSet and print
while (rs.next()){
int id = rs.getInt("id");
String name = rs.getString("name");
String gender = rs.getString("gender");
String address = rs.getString("address");
System.out.println("ID: \t \t" + id);
System.out.println("Name: \t \t" + name);
System.out.println("Gender: \t" + gender);
System.out.println("Address: \t" + address);
System.out.println(" ");
}
// Closing the resultSet
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
public void test(){
int a = "hello";
}
}
You are receiving the error because when you try to call .prepareStatement the connection is closed. Your AccessDBConnect2 class contains a finally block that closes the connection before it returns. Fix that class so it leaves the connection open.
By the way, the JDBC-ODBC Bridge has been removed from Java 8 and is effectively obsolete. You might be interested in this alternative:
Manipulating an Access database from Java without ODBC
I've removed the obviously incorrect answer :) another possibility:
I would think the issue is in your connection to the database, try changing 'C:/Users/Bridget/Documents/EmployeeSys.accdb' to 'C:\\Users\Bridget\Documents\EmployeeSys.accdb'

Connection from CachedRowSet

I have the following Java 7 code to create a CachedRowSet.
CachedRowSet crs = RowSetProvider.newFactory().createCachedRowSet();
Is there a way to get the Connection object from the CachedRowSet object? I would like to set autoCommit to false on the Connection object before invoking the acceptChanges() on CachedRowSet as I'm getting the following exception when invoking acceptChanges().
javax.sql.rowset.spi.SyncProviderException: Can't call commit when autocommit=true
There is a COMMIT_ON_ACCEPT_CHANGES field on CachedRowSet, but it's Deprecated.
Well, it took some time for me to reproduce the issue at my end. Setting the autoCommit value of the Connection to false via conn.setAutoCommit(false); resolved this issue.
Following is the sample working program:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import javax.sql.rowset.CachedRowSet;
import javax.sql.rowset.RowSetProvider;
public class CRSetChecker {
public static void main(String[] args) {
String connectString = "jdbc:oracle:thin:scott/tiger" +
"#(DESCRIPTION=(ADDRESS=(PROTOCOL=tcp)" +
"(HOST=myorahost)(PORT=5521))" +
"(CONNECT_DATA=(SID=myorasid)))";
//Get DB connection
Connection conn = (new CRSet()).getConnection(connectString);
if (conn == null) {
System.out.println("Connection failed");
System.exit(0);
} else {
System.out.println("Connection established successfully!");
try {
CachedRowSet crs =
RowSetProvider.newFactory().createCachedRowSet();
String query="select ename from emp";
crs.setCommand(query);
crs.execute(conn);
//Set auto commit false
conn.setAutoCommit(false);
int count = 0;
while(crs.next()){
String name = crs.getString(1);
count++;
System.out.println(name);
if(count==1){
crs.updateString(1, "COOPER");
crs.updateRow();
crs.acceptChanges(conn);
System.out.println("After update:"+crs.getString(1));
}
}
conn.close();
} catch (SQLException e1) {
e1.printStackTrace();
}
}
}
public Connection getConnection(String connectString)
{
Connection con = null;
try {
try {
Class.forName("oracle.jdbc.OracleDriver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
con = DriverManager.getConnection(connectString);
} catch (SQLException ex) {
ex.printStackTrace();
}
return con;
}
}

Java database application

Can someone help me with this: I'm making a java database application and I want to put my methods for select,insert,update and delete into separated class so they can be called from another classes and reused.
Till now I managed to separate only methods for update and delete and for insert when not using prepared statement. Problem I'm encountering is how to return data's when doing select from database and put them into table.
Here are my update and delete method's in Queries class:
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import com.Konekcija.Konekcija;
public class Queries {
Konekcija konekcija = new Konekcija();
public void updateTable(String sqlQuery){
Connection conn = null;
Statement st = null;
try{
Class.forName("com.mysql.jdbc.Driver");
conn = konekcija.getConn();
st = conn.createStatement();
st.executeUpdate(sqlQuery);
}catch(Exception e){
e.printStackTrace();
}finally{
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
try {
st.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
public void deleteFromTable(String sqlQuery){
Connection conn = null;
Statement st = null;
try{
Class.forName("com.mysql.jdbc.Driver");
conn = konekcija.getConn();
st = conn.createStatement();
st.executeUpdate(sqlQuery);
}catch(Exception e){
e.printStackTrace();
}finally{
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
try {
st.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
P.S. Connection properties are in another class "Konekcija"
You should create a collection and populate it with the results of the query, it should look something like:
List<Foo> selectFoos(Connection connection) throws SQLException {
PreparedStatement ps = connection.prepareStatement("select * from foo");
try {
ResultSet resultSet = ps.executeQuery();
try {
List<Foo> foos = new ArrayList<Foo>();
while (resultSet.next()) {
Foo foo = new Foo();
// use resultSet methods get... to retrieve data from current row of results
// and populate foo
foos.add(foo);
}
} finally {
resultSet.close();
}
} finally {
ps.close();
}
return foos;
}
try executeQuery method. in the java doc for "resultset" class you will find a example:
http://docs.oracle.com/javase/6/docs/api/java/sql/ResultSet.html
Return data for "select from table" would be ResultSet.
You may return the ResultSet to caller and get values (or)
Inside the "Select" method of Queries class retrieve the data from resultset and set it some VO object and add this VO to collection and return the collection (assuming you will get more than one row in ResultSet). For example if you are querying User table, create Java bean class "User" with get/set methods. Set retrieved values to this bean and return it.
//Create User class with get/set in some package.
Class.forName("com.mysql.jdbc.Driver");
conn = konekcija.getConn();
st = conn.createStatement();
ResultSet rs=st.execute(sqlQuery);
//Instantiate user class
while (rs.next())
System.out.println("Name= " + rs.getString("moviename") + " Date= " + String fName = rs.getString("firstName");
User myUser = new User();
myUser.setFirstName(fName);
}
NOTE: This code is hand typed. There may be syntax errors. Please use it as starting point.

Categories