i'm trying to program an application that retrieves data from ms access in java. this is my code:
import java.sql.*;
public class testdb {
public static void main(String[] args) {
String path = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=" + "C:\\smartphone.accdb";
Statement statement;
ResultSet rs;
Connection con;
String sql = "SELECT dev_name,points FROM list";
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con = DriverManager.getConnection(path, "", "");
System.out.println("Connected");
statement = con.createStatement();
statement.executeQuery(sql);
rs = statement.getResultSet();
System.out.println(rs.getString("SELECT dev_name FROM list"));
} catch (Exception ex) {
System.err.println("Got an exception");
System.err.println(ex.getMessage());
}
}
}
it compiles correctly and gives and output of:
Connected
Got an exception
Column not found
please help.
Change
rs.getString("SELECT dev_name FROM list")
to
rs.getString("dev_name")
Also iterare the ResultSet using
while(rs.next())
To iterate the ResultSet you use its next() method. The next() method returns true if the ResultSet has a next record, and moves the ResultSet to point to the next record.If there were no more records, next() returns false.
Related
I am trying to list MySQL databases and their tables with Java. For now, I have two databases as "Database_Services with MySQL_Database_Service, MSSQL_Database_Service, and Directory_Services with Active_Directory, OpenLDAP tables. I get the output for Database_Services and its tables but I do not get the other ones.
public class connectMySQL implements serverConnection{
Connection conn;
Statement stmt;
public void connect(String dbName){
String url;
try {
if(dbName.equals("")){
url = "jdbc:mysql://x:x/";
}
else{
url = "jdbc:mysql://x:x”+ dbName;
}
String username = “x”;
String password = "x";
conn = DriverManager.getConnection(url,username,password);
stmt = conn.createStatement();
}
catch (SQLException ex)
{
System.out.println("An error occurred. Maybe user/password is invalid");
ex.printStackTrace();
}
}
}
public class listInf extends connectMySQL implements listInfrastructure {
public void list() {
String dbName;
ResultSet rs;
try{
connect("");
String str = "SHOW DATABASES";
ResultSet resultSet = stmt.executeQuery(str);
while(resultSet.next()){
dbName = resultSet.getString("Database");
if(!dbName.contains("schema") && !dbName.equals("mysql")){
System.out.println(dbName);
rs = stmt.executeQuery("SHOW TABLES IN " + dbName);
while (rs.next()) {
System.out.println("\t" + rs.getString("Tables_in_" + dbName));
}
}
}
}
catch(SQLException e){
System.out.println("Error");
}
}
}
I want to get an output like:
Database_Services:
MySQL_Database_Service.
MSSQL_Database_Service.
Directory_Services:
Active_Directory_Service.
OpenLDAP_Service.
You are using the same Statement for multiple queries. You cannot do that. From the Javadoc of Statement:
By default, only one ResultSet object per Statement object can be open at the same time. Therefore, if the reading of one ResultSet object is interleaved with the reading of another, each must have been generated by different Statement objects. All execution methods in the Statement interface implicitly close a statment's current ResultSet object if an open one exists.
Connection conn1 = DriverManager.getConnection(url, username, password);
Connection conn2 = DriverManager.getConnection(url, username, password);
Statement statement1 = conn1.createStatement();
Statement statement2 = conn2.createStatement();
ResultSet resultSet1 = statement1.executeQuery("SHOW TABLES IN DB1");
ResultSet resultSet2 = statement2.executeQuery("SHOW TABLES IN DB2");
while (resultSet1.next()) {
System.out.println("");
}
while (resultSet2.next()) {
System.out.println("");
}
if you have more than 2 database, then simply you can use loop for to get the results.
You can use the meta information database information_schema.
SELECT
TABLE_SCHEMA,
TABLE_NAME
FROM information_schema.TABLES
WHERE TABLE_SCHEMA IN ('Database_Services', 'Directory_Services')
ORDER BY TABLE_SCHEMA
I am using XAMPP->Mysql to create database and using Netbeans IDE 8.1 fro create java
My Code
//default package
//1st step
import java.sql.*;
public class DemoJDBC {
public static void main(String[] args) {
try{
String Query = "Select * from Student";
//2nd step
Class.forName("com.mysql.jdbc.Driver");
//3rd step
Connection con = DriverManager.getConnection("jdbc:mysql://localhost/student", "root", "0");
//4th step
Statement st = con.createStatement();
//5th step
ResultSet rs = st.executeQuery(Query);
rs.next();
String name = rs.getString("sname");
System.out.println(name);
//6th step
con.close();
}
catch (Exception e){
}
}
}
Why it didn't show output name ? It just show
"BUILD SUCCESSFUL (total time: 1 second)" in netbeans output
You need to loop through the ResultSet to get the tuples or rows. So while looping you retrieve whatever data or field you want to get. try:
public static void main(String[] args) {
try {
String Query = "Select * from Student";
//2nd step
Class.forName("com.mysql.jdbc.Driver");
//3rd step
Connection con = DriverManager.getConnection("jdbc:mysql://localhost/student", "root", "0");
//4th step
Statement st = con.createStatement();
//5th step
ResultSet rs = st.executeQuery(Query);
//Loop to retrieve tuple(s) from the ResultSet rs
while (rs.next()) {
String name = rs.getString("sname");
System.out.println(name);
}
//6th step
con.close();
} catch (Exception e) {
}
}
NOTE if by default you did not change the password of the root user it is just the empty String (thus "" and not "0"). Other than that you know what you are doing.
Along with the correction of your code to loop through the ResultSet, you also need to correct your connection string as shown below:
Considering that your MySQL is running on the default MySQL port 3306 (which I see that you already are), the connection string needs to be updated.
Also saw that password for the user root is '0', is it really the password?
public static void main(String[] args) {
try {
String query = "SELECT * FROM Student";
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/student", "root", "0");
Statement st = con.createStatement();
ResultSet rs = st.executeQuery(query);
//Loop to retrieve tuple(s) from the ResultSet rs
while (rs.next()) {
String name = rs.getString("sname");
System.out.println(name);
}
con.close();
} catch (Exception e) {
}
}
Also ensure to have your MySQL Connector/J jar file to be present in your CLASSPATH to not to face any reference issues.
Hope that this helps!
I have one problem that in my java programme when i select some record from database,i need records which are not retrun by sql query from database.
suppose i have 5 record in my table and i give 8 record in where condition in my java programme so i need 3 record in ArrayList for that programme did not retrun any values..
My sample programme is as below:-
import java.sql.*;
import java.util.ArrayList;
public class database {
static final String JDBC_DRIVER = "oracle.jdbc.driver.OracleDriver";
static final String DB_URL = "jdbc:oracle:thin:#localhost:1521:orcl";
static final String USER = "asiftest";
static final String PASS = "asif";
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
conn = DriverManager.getConnection(DB_URL,USER,PASS);
ArrayList ar =new ArrayList();
System.out.println("Creating statement...");
stmt = conn.createStatement();
String sql;
sql = "SELECT contractno FROM temp_survival where contractno in ('77777','11111','22222','33333','44444','55555','66666','77777','363636','25252')";
ResultSet rs = stmt.executeQuery(sql);
while(rs.next()){
String first = rs.getString("contractno");
System.out.print("contractno: " + first);
}
rs.close();
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();
}
}
}
}
For the above programme i am getting values for '77777','11111','22222','33333','44444','55555','66666','77777' but for next 2 records '363636','25252' i am are not getting values because that is not available in database table so i need to add them in arraylist in above proramme. Please help me
Make a List for input contact numbers (which you are passing in where clause)
Make a List of contact numbers which you are getting in the query results
Use CollectionUtils.substract(list1, list2)
I am having problem retrieving OUT parameter from mysql stored procedure in java.
CALL proc_after_topic_add('newtest',#result);
SELECT #result;
this query gives me desired out parameter but how would i retrieve it in java.I tried using CallableStatement but i get
java.sql.SQLException: Callable statments not supported.
error.Please guys help me.
I have tried following
String sql = "CALL proc_after_topic_add(?,?);";
CallableStatement cstmt = conn.prepareCall(sql);
cstmt.setString(1, topicname);
cstmt.registerOutParameter(2, java.sql.Types.INTEGER);
ResultSet rs = cstmt.executeQuery();
if (rs.next()) {
if (rs.getInt(1) == 1) {
res = 0;
} else {
res = -1;
}
}
I havent posted stored procedure code because there is nothing wrong with it.
PS:I a using mysql 5.5.21 and yes i should probably mention i am using mysql connector 3.0.15
Okay this is solved.For anyone who encounters the same problem,just download latest version of mysql connector.
Error in this line
cstmt.registerOutParameter(2, java.sql.Types.INTEGER);
change like this
String sql = "CALL proc_after_topic_add(?,?);";
cstmt.registerOutParameter(2, java.sql.Types.INTEGER);
Create a schema test and create a table employee in schema with 2 columns.
id and employeename and insert some data.
Use this Stored Procedure.
DELIMITER $$
DROP PROCEDURE IF EXISTS `test`.`get_count_name1` $$
CREATE PROCEDURE `test`.`get_count_name1`(IN the_name VARCHAR(64),OUT
the_count INT)
BEGIN
SELECT COUNT(*) INTO the_count from employee where employeename=the_name;
END$$
DELIMITER ;
Use this example.
username and password are root and root for me. change as per your
requirement. Here i am counting the occurence of employeename="deepak"
import java.sql.*;
public class JDBCExample {
// JDBC driver name and database URL
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost/test";
// Database credentials
static final String USER = "root";
static final String PASS = "root";
public static void main(String[] args) {
Connection conn = null;
CallableStatement stmt = null;
try{
//STEP 2: Register JDBC driver
Class.forName("com.mysql.jdbc.Driver");
//STEP 3: Open a connection
System.out.println("Connecting to database...");
conn = DriverManager.getConnection(DB_URL,USER,PASS);
//STEP 4: Execute a query
System.out.println("Creating statement...");
String sql = "{call get_count_name1 (?, ?)}";
stmt = conn.prepareCall(sql);
//Bind IN parameter first, then bind OUT parameter
String name = "Deepak";
stmt.setString(1, name); // This would set ID as 102
// Because second parameter is OUT so register it
stmt.registerOutParameter(2, java.sql.Types.INTEGER);
//Use execute method to run stored procedure.
System.out.println("Executing stored procedure..." );
stmt.execute();
int count=stmt.getInt(2);
System.out.println(count);
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(SQLException se){
se.printStackTrace();
}//end finally try
}//end try
System.out.println("Goodbye!");
}//end main
}//end JDBCExample
I've connected to a MySQL database, which contains four fields (the first of which being an ID, the latter ones each containing varchar strings).
I am trying to get the last row of the database and retrieve the contents of the fields so that I can set them to variables (an int and three strings) and use them later.
So far, I have the bare minimum to make the connection, where do I go from here? As you can see I have tried to write a SQL statement to get the last row but it's all gone wrong from there and I don't know how to split it into the separate fields.
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection con = DriverManager.getConnection("jdbc:mysql://localhost/t", "", "");
Statement st = con.createStatement();
String sql = ("SELECT * FROM posts ORDER BY id DESC LIMIT 1;");
st.getResultSet().getRow();
con.close();
Here you go :
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection con = DriverManager.getConnection("jdbc:mysql://localhost/t", "", "");
Statement st = con.createStatement();
String sql = ("SELECT * FROM posts ORDER BY id DESC LIMIT 1;");
ResultSet rs = st.executeQuery(sql);
if(rs.next()) {
int id = rs.getInt("first_column_name");
String str1 = rs.getString("second_column_name");
}
con.close();
In rs.getInt or rs.getString you can pass column_id starting from 1, but i prefer to pass column_name as its more informative as you don't have to look at database table for which index is what column.
UPDATE : rs.next
boolean next()
throws SQLException
Moves the cursor froward one row from its current position. A
ResultSet cursor is initially positioned before the first row; the
first call to the method next makes the first row the current row; the
second call makes the second row the current row, and so on.
When a call to the next method returns false, the cursor is positioned
after the last row. Any invocation of a ResultSet method which
requires a current row will result in a SQLException being thrown. If
the result set type is TYPE_FORWARD_ONLY, it is vendor specified
whether their JDBC driver implementation will return false or throw an
SQLException on a subsequent call to next.
If an input stream is open for the current row, a call to the method
next will implicitly close it. A ResultSet object's warning chain is
cleared when a new row is read.
Returns:
true if the new current row is valid; false if there are no more rows Throws:
SQLException - if a database access error occurs or this method is called on a closed result set
reference
Something like this would do:
public static void main(String[] args) {
Connection con = null;
Statement st = null;
ResultSet rs = null;
String url = "jdbc:mysql://localhost/t";
String user = "";
String password = "";
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection(url, user, password);
st = con.createStatement();
rs = st.executeQuery("SELECT * FROM posts ORDER BY id DESC LIMIT 1;");
if (rs.next()) {//get first result
System.out.println(rs.getString(1));//coloumn 1
}
} catch (SQLException ex) {
Logger lgr = Logger.getLogger(Version.class.getName());
lgr.log(Level.SEVERE, ex.getMessage(), ex);
} finally {
try {
if (rs != null) {
rs.close();
}
if (st != null) {
st.close();
}
if (con != null) {
con.close();
}
} catch (SQLException ex) {
Logger lgr = Logger.getLogger(Version.class.getName());
lgr.log(Level.WARNING, ex.getMessage(), ex);
}
}
}
you can iterate over the results with a while like this:
while(rs.next())
{
System.out.println(rs.getString("Colomn_Name"));//or getString(1) for coloumn 1 etc
}
There are many other great tutorial out there like these to list a few:
http://www.vogella.com/articles/MySQLJava/article.html
http://www.java-samples.com/showtutorial.php?tutorialid=9
As for your use of Class.forName("com.mysql.jdbc.Driver").newInstance(); see JDBC connection- Class.forName vs Class.forName().newInstance? which shows how you can just use Class.forName("com.mysql.jdbc.Driver") as its not necessary to initiate it yourself
References:
http://zetcode.com/databases/mysqljavatutorial/
This should work, I think...
ResultSet results = st.executeQuery(sql);
if(results.next()) { //there is a row
int id = results.getInt(1); //ID if its 1st column
String str1 = results.getString(2);
...
}
Easy Java method to get data from MySQL table:
/*
* CREDIT : WWW.CODENIRVANA.IN
*/
String Data(String query){
String get=null;
try{
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection con = (Connection)DriverManager.getConnection
("jdbc:mysql://localhost:3306/mysql","root","password");
Statement stmt = (Statement) con.createStatement();
ResultSet rs=stmt.executeQuery(query);
if (rs.next())
{
get = rs.getString("");
}
}
catch(Exception e){
JOptionPane.showMessageDialog (this, e.getMessage());
}
return get;
}
Here is what I just did right now:
import java.sql.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import com.sun.javafx.runtime.VersionInfo;
public class ConnectToMySql {
public static ConnectBean dataBean = new ConnectBean();
public static void main(String args[]) {
getData();
}
public static void getData () {
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/mynewpage",
"root", "root");
// here mynewpage is database name, root is username and password
Statement stmt = con.createStatement();
System.out.println("stmt " + stmt);
ResultSet rs = stmt.executeQuery("select * from carsData");
System.out.println("rs " + rs);
int count = 1;
while (rs.next()) {
String vehicleType = rs.getString("VHCL_TYPE");
System.out.println(count +": " + vehicleType);
count++;
}
con.close();
} catch (Exception e) {
Logger lgr = Logger.getLogger(VersionInfo.class.getName());
lgr.log(Level.SEVERE, e.getMessage(), e);
System.out.println(e.getMessage());
}
}
}
The Above code will get you the first column of the table you have.
This is the table which you might need to create in your MySQL database
CREATE TABLE
carsData
(
VHCL_TYPE CHARACTER(10) NOT NULL,
);
First, Download MySQL connector jar file, This is the latest jar file as of today [mysql-connector-java-8.0.21].
Add the Jar file to your workspace [build path].
Then Create a new Connection object from the DriverManager class, so you could use this Connection object to execute queries.
Define the database name, userName, and Password for your connection.
Use the resultSet to get the data based one the column name from your database table.
Sample code is here:
public class JdbcMySQLExample{
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/YOUR_DB_NAME?useSSL=false";
String user = "root";
String password = "root";
String query = "SELECT * from YOUR_TABLE_NAME";
try (Connection con = DriverManager.getConnection(url, user, password);
Statement st = con.createStatement();
ResultSet rs = st.executeQuery(query)) {
if (rs.next()) {
System.out.println(rs.getString(1));
}
} catch (SQLException ex) {
System.out.println(ex);
}
}