delete duplicates method wont delete duplicates - java

I have written a method that executes a query that deletes duplicates in a MS Access file. The query works properly when run in MS Access but nothing happens when it is run through java. Other querys work using this same connection string. Can another set of eyes see what is causing this to happen?
public static void delete_duplicates() throws Exception{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String sDBQ = "C:/AW.mdb";
String database = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=" + sDBQ + ";DriverID=22;READONLY=true";
Connection conn = DriverManager.getConnection( database ,"","");;
Statement stmt = conn.createStatement();
String query = "DELETE "+
"FROM AW " +
"WHERE id not in (select min(id) from AW group by Symbol, Direction, START_DT, END_DT)";
System.out.println(query);
stmt.executeUpdate(query);
stmt.close();
}

You are connecting like this:
String database = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=" + sDBQ + ";DriverID=22;READONLY=true";
You have an attribute READONLY set to true, so you cannot make modifications to your database.

Related

multiple sql command

I'm trying to execute multiple sql commands, but it gives me "error in your SQL syntax;"
Db_Connection dbconn = new Db_Connection();
Connection myconnection = dbconn.Connection();
String sqlString = "SELECT DISTINCT std_id FROM std_crs WHERE crs_id ='222123'; "
+ "SELECT * FROM cplus_grades ;";
Statement myStatement = myconnection.createStatement();
boolean results = myStatement.execute(sqlString);
do {
if (results) {
ResultSet rs = myStatement.getResultSet();
while (rs.next()) {
}
rs.close();
}
results = myStatement.getMoreResults();
} while(results);
myStatement.close();
I did a small test with three JDBC drivers:
MS SQL: works, returns two result sets
MySQL: fails with a syntax error - that is what you are seeing
HSQLDB: runs, but returns only one result set.
So I guess it simply depends on the JDBC driver if this technique works. Maybe it works only in MS SQL JDBC.
UPDATE:
It also works with Postgres.
please
1. String dbUrl = "jdbc:mysql://yourDatabase?allowMultiQueries=true";
this should be your jdbc connection url

How to list all tables' name in MSAccess database file using sql query in java?

I've getting some code here
String url = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=" + f.getPath() + ";";
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection conn = DriverManager.getConnection(url);
Statement st=conn.createStatement();
String query="SELECT name FROM MSysObjects WHERE Type=1 AND Flags=0";
ResultSet rs=st.executeQuery(query);
ArrayList<String> tableNames=new ArrayList<String>();
while(rs.next()){
String name=rs.getString(1);
tableNames.add(name);
}
but there has some problem
[Microsoft][ODBC Microsoft Access Driver] Record(s) cannot be read; no read permission on 'MSysObjects'."
and I searched for this problem and Just found this: social.msdn.microsoft.com/Forums/sqlserver/en-US/… "
Because MSysObjects is a system table in Access, the Admin user does not have permission to read data in it".
I read the answer, but in fact, I want to access permission by programming, does anyone can help me? Thank you very much
Seems that Access does not allow to query MSysObjects. Did you follow the steps in the article to give your user the adequate permission?
Anyway JDBC also has an own API which allows you to read database metadata:
Connection conn = ...
DatabaseMetaData metaData = conn.getMetaData();
ResultSet rs = metaData.getTables(null, null, "%", null);
while (rs.next()) {
String name = rs.getString(3); // see javadoc of DatabaseMetaData
tableNames.add(name);
}

Not able to execute the Create table sql query through java

I am trying to create the table through java string but it is displaying error as table doesn't exist but when I run the same query directly on workbench it runs fine. Below is my code
String url = "jdbc:mysql://localhost:3306/" ;
String dbname = "tweetmap";
String username = "root";
String password = "root";
try
{
// SQL Driver needed for connecting to Database
Class.forName("com.mysql.jdbc.Driver");
c = DriverManager.getConnection(url+dbname,username,password);
c.setAutoCommit(true);
stmt = c.createStatement();
//Creating the Database if not Already Present
String sql = "CREATE TABLE if not exists senti "
+ "( latitude double NULL, "
+ "longitude double NULL, "
+ "Sentiment TEXT NULL) ";
stmt.executeUpdate(sql);
if(sentiment != null){
stmt1 = c.createStatement();
stmt1.executeUpdate("INSERT INTO `senti`(latitude,longitude,Sentiment) VALUE ('"+lati+"','"+longi+"','"+sentiment+"')");
}
}
catch(Exception e){
e.printStackTrace();
}
this is the problem stmt.executeUpdate(sql);
instead of executeUpdate use execute(String SQL) method.
execute(String SQL) is used for DDL/DML statement
while executeUpdate(String SQL) is used only for DML operation
Best way to execute any query in JDBC is using execute() method. This method can be used for any kind of query.
I hope below link will help you to understand more.
http://docs.oracle.com/javase/7/docs/api/java/sql/Statement.html#execute(java.lang.String)

postgres how to get data from multiple databases

i have 2 PostgreSQL databases on different port: DB1 on port 5432 and DB2 on port 5431
and i have code to get data from DB1 like this :
try {
Class.forName("org.postgresql.Driver");
String conString = "jdbc:postgresql://127.0.0.1:5432/DB1?user=MyUser&pass=MyPass" ;
c = DriverManager.getConnection(conString);
st = c.createStatement();
ResultSet rs = st.executeQuery(query);
while (rs.next()){
vaArrL.add(rs.getDouble("va"));
vbArrL.add(rs.getDouble("vb"));
vcArrL.add(rs.getDouble("vc"));
}
and work good when i send singe query to DB1 only.
but now, i have query to both databases together like :
select va, vb from DB1.public.t1 where datatime >= 1417384860 and datatime <= 1417381199
union
select va, vb from dblink('hostaddr=127.0.0.1 port=5431 dbname=DB2 user=MyUser password =MyPass '::text,
'select va, vb
from Db2.public.t2 order by datatime ')
datos(va integer,vb integer);
when i run query from pgAdmin i get result
but when i sent query to gunction i get : connection not available
Now. How can i send my query to function and i get values?
Can you try using JDBC's setCatalog method?
setCatalog's javadoc states that:
Calling setCatalog has no effect on previously created or prepared
Statement objects. It is implementation defined whether a DBMS prepare
operation takes place immediately when the Connection method
prepareStatement or prepareCall is invoked. For maximum portability,
setCatalog should be called before a Statement is created or prepared.
try {
Class.forName("org.postgresql.Driver");
// Connect to DB1 (specified in connection string/URL).
String conString = "jdbc:postgresql://127.0.0.1:5432/DB1?user=MyUser&pass=MyPass" ;
c = DriverManager.getConnection(conString);
st = c.createStatement();
// Execute query on DB1.
ResultSet rs = st.executeQuery(query);
while (rs.next()){
vaArrL.add(rs.getDouble("va"));
vbArrL.add(rs.getDouble("vb"));
vcArrL.add(rs.getDouble("vc"));
}
// Switch to DB2 and execute query.
c.setCatalog("DB2");
Statement st2 = c.createStatement();
ResultSet rs2 = st2.executeQuery(...);
}
If the JDBC driver doesn't support setCatalog, then you can execute the SQL query USE DB2 explicitly but this might affect already open statements (I'm not sure about this).
Edit: OP wants all results from both databases in the same ResultSet.
Assuming that DB1 and DB2 are on same server, I'd recommend creating a view in database DB1 which can access tables in database DB2 and return combined results. Then you can just SELECT * from the view via JDBC and get the results.
You can use a query like this for your view (assuming that the view is created in DB1):
SELECT all.va, all.vb FROM
(SELECT va, vb, datatime FROM t2
UNION
SELECT va, vb, datatime FROM DB2.public.t2) all
ORDER BY all.datatime
Note: To access a table in another database, you need to specify [db-name].[schema].[tablename].
If your query needs dynamic arguments, then you can create a stored procedure instead of a view.
i am find 1 solution
i am use 2 connection and send to query from client to xmlrpc server, here :
String conString = "jdbc:postgresql://" + host + ":" + port + "/" + DBName +
"?user=" + user + "&pass=" + pass;
String conString1 = "jdbc:postgresql://" + host + ":" + port2 + "/" + DBName2 +
"?user=" + user + "&pass=" + pass;
c = DriverManager.getConnection(conString);
c2 = DriverManager.getConnection(conString1);
st = c.createStatement();
st2 = c2.createStatement();
List<ResultSet> resultSets = new ArrayList<>();
resultSets.add(st.executeQuery(query));
resultSets.add(st2.executeQuery(query2));
ResultSets rs = new ResultSets(resultSets);
while (rs.next()){
unbArrL.add(rs.getUnbalance("unbalance"));
}
and resultSets class to get values from DB is :
class ResultSets {
private java.util.List<java.sql.ResultSet> resultSets;
private java.sql.ResultSet current;
public ResultSets(java.util.List<java.sql.ResultSet> resultSets) {
this.resultSets = new java.util.ArrayList<>(resultSets);
current = resultSets.remove(0);
}
public boolean next() throws SQLException {
if (current.next()) {
return true;
}else if (!resultSets.isEmpty()) {
current = resultSets.remove(0);
return next();
}
return false;
}
public Double getUnbalance(String unbalance) throws SQLException{
return current.getDouble("unbalance");
}
}

No Database selected when retrieving from mysql website

I have a mysql database that I am trying to retrieve from our website host (godaddy). I followed a format that seems to be right but it tells me that:
java.sql.SQLException: No database selected
Code:
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
try {
// STEP 2: Register JDBC driver
Class.forName(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...");
stmt = conn.createStatement();
String sql;
sql = "SELECT * FROM item_master";
ResultSet rs = stmt.executeQuery(sql); //<-- This is where the error is.
// STEP 5: Extract data from result set
while (rs.next()) {
// Retrieve by column name
int id = rs.getInt("id");
// Display values
System.out.print("ID: " + id);
}
...
}
I did a print statement of the conn to maybe think the connection could of been null and was shown this:
com.mysql.jdbc.JDBC4Connection#2a6*****
Anyone have any ideas what could cause something like this?
Your URL for your database should include your database name. This is normally your URL followed by a "/DBNAME".
String URL = "jdbc:mysql://localhost:3306/mydb";
Where "mydb" is your database name.
What is the value of DB_URL? As far as I am aware, the URL needs to be of the form:
"WEBURL/DATABASENAME:PORT"
Are you just trying to connect to the WEBURL, without specifying a DATABASE?
I had the same problem.
Just run one more query (before your 'SELECT' statement) to connect to your database.
First:
sql = "USE <yourdatabase>";
ResultSet rs = stmt.executeQuery(sql);
And after:
sql = "SELECT * FROM item_master";
rs = stmt.executeQuery(sql);

Categories

Resources