This question already has an answer here:
Closed 10 years ago.
Possible Duplicate:
Accessing Access over JDBC (using ODBC?)
I have to do this since we have an unknown amount of access databases the user can select using our program so as to process data from them.
Here is connection code:
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver").newInstance();
String database = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=ACCESS_FILE_PATH/FILE_NAME.mdb";
connection = DriverManager.getConnection( database ,"username","password");
I did it as the following:
first , create a db DB1.MDB which contain a table named "table1";
second, config ODBC , create DatabaseSource named "Access2000"。
import java.sql.*;
class database {
public static void main(String args[]) {
try{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String url="jdbc:odbc:Access2000";
Connection connection=DriverManager.getConnection(url);
Statement statement = connection.createStatement();
String sql="SELECT * FROM table1";
ResultSet rs = statement.executeQuery(sql);
String tt;
while (rs.next()) {
System.out.print("name:" + rs.getString("Name"));
System.out.println("age:" + rs.getString("Age"));
}
rs.close();
connection.close();
}
catch(Exception ex){
System.out.println(ex);
System.exit(0);
}
}
}
Related
This question already has answers here:
Connect Java to a MySQL database
(14 answers)
Closed 2 years ago.
So I am trying to make a connection with JDBC using XAMPP, but it doesn't work, What am I doing wrong here?
public static void main(String args[]) {
try {
Connection myConn = DriverManager.getConnection(
"http://localhost/phpmyadmin/sql.php?db=a3_eindopdracht_2&table=namen&pos=0", "", "");
Statement myStm = myConn.createStatement();
ResultSet myRs = myStm.executeQuery("SELECT * FROM namen");
while (myRs.next()) {
System.out.println(myRs.getString("voornaam") + " " + myRs.getString("achternaam"));
}
} catch (Exception exc) {
exc.printStackTrace();
}
Firstly, you don't find Driver. You have to load them, by calling the Drive class like that :
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
// Cannot find driver for MySQL
}
Then, you are trying to connect to your databse with HTTP protocol. But, DB have they own (with port 3306 by default), so you have to use address like that:
jdbc:mysql://myserver.com/schema
Finally: don't forget to add username and password on last 2 fields of getConnection method
This question already has answers here:
The infamous java.sql.SQLException: No suitable driver found
(21 answers)
No suitable driver found for 'jdbc:mysql://localhost:3306/mysql [duplicate]
(8 answers)
Closed 5 years ago.
import java.sql.*;
class Mysqll{
public static void main(String args[]){
try{
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc::mysql://localhost:3306/asd","root","qwerty");
Statement st = con.createStatement();
ResultSet rs = st.executeQuery("select * from abc");
while(rs.next())
{
System.out.println(rs.getInt(1) + " " + rs.getString(2));
}
con.close();
}
catch(Exception e)
{
System.out.println(e);
}
}
}
I am new to jdbc programming. So plese help.
Getting this Exception while running the program.
java.sql.SQLException: No suitable driver found for jdbc::mysql://localhost:3306/asd
I had copied mysql-connector.jar file into jre/lib/ext folder.
Thanx in advance.
The connection string being passed to DriverManager is a URL. The formatting matters, and your problem is due to an extra colon between jdbc and mysql (verified by testing on my own system).
Replace jdbc::mysql: with jdbc:mysql:.
This question already has an answer here:
Manipulating an Access database from Java without ODBC
(1 answer)
Closed 6 years ago.
I want to be able to import the data in the database into blue J and run queries and then display the results to the user. However, I want to do this without the use of an ODBC DSN and an SQL server. I just want to be able to search the database using SQL directly. Is there a way I can do this? I have imported the SQL library, but am not sure how to use this to link to the database I have made. Thank you in advance
The standard way to access a relational database in Java is by using JDBC. There is a lot of tutorials.
for exemple (for a MySQL DB):
public Connection getConnection() throws ClassNotFoundException, SQLException {
Class.forName("com.mysql.jdbc.Driver");
// could be an IP address, including localhost instead of an URL
return DriverManager.getConnection("jdbc:mysql://my-url.com:3306/my_database", "user", "password");
}
public void test() throws ClassNotFoundException, SQLException {
try(Connection c = getConnection()) {
try (PreparedStatement ps = c.prepareStatement("SELECT id, name FROM person WHERE email = ?")) {
ps.setString(1, "john.doe#mail.com");
try (ResultSet rs = ps.executeQuery()) {
while (rs.next()) {
Integer id = rs.getInt("id");
String name = rs.getString("name");
System.out.println(id + " " + name);
}
}
}
}
}
The jar of the Driver has to be in the class path
Edit
UcanAccess is JDBC Driver for MS-Access
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
This question already has answers here:
java.sql.SQLException: No database selected - why?
(4 answers)
Closed 3 years ago.
why this program is not executing when it goes in to the do while loop second time and why it is giving the exception "Exception java.sql.SQLException: [MySQL][ODBC 5.1 Driver][mysqld-5.0.51a-community-nt]No database selected"
//import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Scanner;
import java.util.Vector;
public class DataBase {
public void LoadDriver() {
// Load the JDBC-ODBC bridge driver
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
} catch (ClassNotFoundException ee) {
ee.printStackTrace();
}
}
// 2.open a data source name by means of the jdbcodbcdriver.
static void connect() throws SQLException {
// Connect to the database
Connection con = DriverManager.getConnection("jdbc:odbc:MySQL", "root", "admin");
Statement stmt = con.createStatement();
// Shut off autocommit
con.setAutoCommit(false);
System.out.println("1.Insert 2.Delete 3.Update 4.Select");
Scanner s = new Scanner(System.in);
int x;
x = s.nextInt();
String query; // SQL select string
ResultSet rs; // SQL query results
boolean more; // "more rows found" switch
String v1, v2; // Temporary storage results
Vector<Object> results = new Vector<Object>(10);
if (x == 1) {
try {
stmt.executeUpdate("INSERT INTO employee( emp_id,emp_name ) VALUES ( '122','shiva' ) ");
} catch(Exception e){System.out.println("Exception " +e);e.printStackTrace();}
}
if (x == 2) {
try {
stmt.executeUpdate("DELETE from employee where emp_id='102' ");
}catch(Exception e){System.out.println("Exception "+e);e.printStackTrace();}
}
if (x == 3) {
try {
stmt
.executeUpdate("UPDATE employee SET emp_name = 'madavan' where emp_id='20'; ");
} catch(Exception e){System.out.println("Exception "+e);e.printStackTrace();}
}
query = "SELECT * FROM employee ";
try {
rs = stmt.executeQuery(query);
// Check to see if any rows were read
more = rs.next();
if (!more) {
System.out.println("No rows found.");
return;
}
// Loop through the rows retrieved from the query
while (more) {
v1 = "ID: " + rs.getInt("emp_id");
v2 = "Name: " + rs.getString("emp_name");
System.out.println(v1);
System.out.println(v2);
System.out.println("");
results.addElement(v1 + "\n" + v2 + "\n");
more = rs.next();
}
rs.close();
} catch (SQLException e) {
System.out.println("" + results.size() + "results where found.");
}
finally{stmt.close();}
}
public static void main(String[] args) throws SQLException {
String str = "y";
do {
DataBase s = new DataBase();
s.LoadDriver();
DataBase.connect();
Scanner sc = new Scanner(System.in);
System.out.println("DO u Want to PROCEED TO QUERY : ");
str = sc.next();
} while (str !="n");
}
}
Unless you have to use the jdbc/odbc driver I would use the straight mysql jdbc driver. You can download it free from mysql.
then
public void LoadDriver() {
// Load the JDBC-ODBC bridge driver
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException ee) {
ee.printStackTrace();
}
}
static void connect() throws SQLException {
// Connect to the database
Connection con = DriverManager.getConnection("jdbc:mysql:host/databasename", "root", "admin");
Statement stmt = con.createStatement();
...
Just from looking at the exception.. I would guess that you are not specifying the database.
How can you do a select on a table without telling it which schema to select from ?
This is typically set in the connection string..
Is the ODBC source actually set up to select a database? eg. can you access the database through another ODBC client tool?
If you need to select a database explicitly in the JDBC string you can do that using the ‘database’ parameter.
But having the database chosen in the ODBC setup would be more usual. And indeed, as Clint mentioned, using the normal MySQL JDBC driver instead of ODBC would be more usual still.
while (str !="n")
That's not how you compare strings in Java.
Found a bug listing at MySQL that gives this error but with different technologies. However, in the description it indicates that it is related to reauthorization not sending the database information, so perhaps that is what you are encountering here as well.
Some things that stick out as odd to me (although no clue if they will have any impact on your error)
You only need to load the Driver Manager once
You aren't closing your connection, so either close it or refactor to use the same one.
Perhaps move these two lines to just before the do loop
DataBase s = new DataBase();
s.LoadDriver();