How to execute Multiple "Create Table... " Statements in ACCESS Database - ms-access

I have 480 "Create table" statements to be inserted into an empty access db. I found the access has no option of multiple query executions...
I have all the create table queries in a text file
Please help me, how can this be achieved.
I am using MS Access 2007. The access db is in local harddrive
Thanks
Ramm

I did this java sample. It worked.. Please let me know if any simple process for this.
import java.io.*;
import java.util.*;
import java.text.*;
import java.sql.*;
import org.apache.poi.ss.usermodel.*;
public class DirReader_fat {
public static void main(String[] args) {
String inputFilePath = "D:\\Sample.xlsx";
String strInputQuery = "";
try{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String filename = "d:\\Empty_1.mdb";
String database = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=";
database+= filename.trim() + ";DriverID=22;READONLY=true}"; // add on to the end
// now we can get the connection from the DriverManager
Connection con = DriverManager.getConnection( database ,"","");
// try and create a java.sql.Statement so we can run queries
Statement s = con.createStatement();
InputStream inputStream = new FileInputStream(new File(inputFilePath));
Workbook wb = WorkbookFactory.create(inputStream);
Sheet sheet = wb.getSheet("Sheet1");
for (Row row : sheet) {
strInputQuery = row.getCell(0).toString();
s.execute(strInputQuery);
}
}catch (Exception e) {
e.printStackTrace();
}
}
}
Thanks
Ramm

Related

JDBC executeQuery returns empty ResultSet even though there is data?

import java.sql.*;
public class Driver {
public static void main(String[] args) {
try {
Connection myConn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb?autoReconnect=true&useSSL=false",
"root", "password");
Statement myStamement = myConn.createStatement();
ResultSet myRs = myStamement.executeQuery("SELECT * FROM table1");
while(myRs.next()) {
System.out.println("I GOT SOMETHING FROM DATABASE");
System.out.println(myRs.getString("id"));
}
}
catch (Exception exc) {
exc.printStackTrace();
}
}
}
and I have setup my SQL server and can see the same query in mySQL workbench here:
enter image description here
It doesn't give me an error connecting to the database else it would go to catch.
It returns an empty ResultSet else it would go into while loop once.
There is data in my database that I can see from using same command in photo photo.

What's wrong with Google endpoints -- Cloud SQL connection?

I'm trying to connect from a Google Endpoints server to a Google Cloud SQL server. I'm modifying the Greetings.getGreeting() method in this tutorial:
https://cloud.google.com/appengine/docs/java/endpoints/getstarted/backend/helloendpoints
to call the Cloud mysql database as demonstrated in this tutorial (see doGet method):
https://cloud.google.com/appengine/docs/java/cloud-sql/#enable_connector_j
I have made sure that I can connect to the database from my machine mysql client. The database instance "simple" has a single table "simpletable" who's rows hold an entityID and a string. (But I'm not able to connect, so that's not too important yet.)
This is my endpoints code:
package com.example.helloendpoints;
import com.google.api.server.spi.config.Api;
import com.google.api.server.spi.config.ApiMethod;
import com.google.api.server.spi.response.NotFoundException;
import com.google.appengine.api.users.User;
import java.sql.*;
import java.util.ArrayList;
import javax.inject.Named;
/**
* Defines v1 of a helloworld API, which provides simple "greeting" methods.
*/
#Api(
name = "helloworld",
version = "v1",
scopes = {Constants.EMAIL_SCOPE},
clientIds = {Constants.WEB_CLIENT_ID,
Constants.ANDROID_CLIENT_ID,
Constants.IOS_CLIENT_ID,
Constants.API_EXPLORER_CLIENT_ID},
audiences = {Constants.ANDROID_AUDIENCE}
)
public class Greetings {
public static ArrayList<HelloGreeting> greetings = new ArrayList<HelloGreeting>();
static {
greetings.add(new HelloGreeting("hello world!"));
greetings.add(new HelloGreeting("goodbye world!"));
}
public HelloGreeting getGreeting(#Named("id") Integer id) throws NotFoundException {
// pair to use when running local endpoint server
String urlFromDev = "jdbc:mysql://173.194.XXX.90:3306/simple?user=root";
String classForNameFromDev = "com.mysql.jdbc.Driver";
// pair to use when running cloud endpoint server
String classForNameFromCloud = "com.mysql.jdbc.GoogleDriver";
String urlFromCloud = "jdbc:google:mysql://"
+ Constants.PROJECT_ID + ":"
+ Constants.CLOUD_SQL_INSTANCE_NAME +"/"
+ Constants.DATABASE_NAME + "?user=root";
HelloGreeting helloGreeting = new HelloGreeting();
try {
Class.forName(classForNameFromDev);
// Class.forName(classForNameFromCloud);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
try {
Connection connection = DriverManager.getConnection(urlFromDev);
// Connection connection = DriverManager.getConnection(urlFromCloud);
try {
String statement = "Select simplestring from simpletable where entryID = ?";
PreparedStatement preparedStatement = connection.prepareStatement(statement);
preparedStatement.setInt(1, id);
ResultSet resultSet = preparedStatement.executeQuery();
if (!resultSet.wasNull()) {
helloGreeting.setMessage(resultSet.getString("simplestring"));
} else {
throw new NotFoundException("Greeting not found with an index: " + id);
}
} finally {
connection.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
return helloGreeting;
}
#ApiMethod(name = "greetings.multiply", httpMethod = "post")
public HelloGreeting insertGreeting(#Named("times") Integer times, HelloGreeting greeting) {
HelloGreeting response = new HelloGreeting();
StringBuilder responseBuilder = new StringBuilder();
for (int i = 0; i < times; i++) {
responseBuilder.append(greeting.getMessage());
}
response.setMessage(responseBuilder.toString());
return response;
}
#ApiMethod(name = "greetings.authed", path = "hellogreeting/authed")
public HelloGreeting authedGreeting(User user) {
HelloGreeting response = new HelloGreeting("hello " + user.getEmail());
return response;
}
}
I have tried to enable mysql connector/j in my appengine-web.xml
<?xml version="1.0" encoding="utf-8"?>
<appengine-web-app xmlns="http://appengine.google.com/ns/1.0">
<use-google-connector-j>true</use-google-connector-j>
<application>backendapitutorial-1XXX</application>
<version>${app.version}</version>
<threadsafe>true</threadsafe>
<system-properties>
<property name="java.util.logging.config.file" value="WEB- INF/logging.properties"/>
</system-properties>
</appengine-web-app>
Whichever way I build+depl0y it (Dev or cloud), I always get
java.sql.SQLException: No suitable driver found for jdbc:mysql://173.194.XXX.90:3306/simple?user=root
or
java.sql.SQLException: No suitable driver found for jdbc:google:mysql://backendapitutorial-XXXX:simple/simple?user=root
(I replaced the real IP and project name with "X"s for this post).
I've already looked at these:
java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost:3306/dbname
ClassNotFoundException: com.mysql.jdbc.GoogleDriver
What does 'Class.forName("org.sqlite.JDBC");' do?
I'm building with Maven and working on IntelliJ IDE.
Any help is greatly appreciated. Thanks.

Unable to get the hive remote metastore table information over thrift

I can get the metastore table information on my local mysql metastore setup with hive using the below program.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hive.conf.HiveConf;
import org.apache.hadoop.hive.conf.HiveConf.ConfVars;
public class MetaStoreTest {
public static void main(String[] args) throws Exception {
Connection conn = null;
try {
HiveConf conf = new HiveConf();
conf.addResource(new Path("/home/hadoop/hive-0.12.0/conf/hive-site.xml"));
Class.forName(conf.getVar(ConfVars.METASTORE_CONNECTION_DRIVER));
conn = DriverManager.getConnection(
conf.getVar(ConfVars.METASTORECONNECTURLKEY),
conf.getVar(ConfVars.METASTORE_CONNECTION_USER_NAME),
conf.getVar(ConfVars.METASTOREPWD));
Statement st = conn.createStatement();
ResultSet rs = st.executeQuery(
"select t.tbl_name, s.location from TBLS t " +
"join SDS s on t.sd_id = s.sd_id");
while (rs.next()) {
System.out.println(rs.getString(1) + " : " + rs.getString(2));
}
}
finally {
if (conn != null) {
conn.close();
}
}
}
}
Currently am trying the above program to get the metastore tables from a remote metastore using thrift.In my current hive-site.xml i have these params,
hive.metastore.uris = thrift://host1:9083, thrift://host2:9083
hive.metastore.local = false
There is no params for :
javax.jdo.option.ConnectionDriverName, javax.jdo.option.ConnectionUserName, javax.jdo.option.ConnectionPassword
So, how can i fetch the metatable information over thrift protocol. I am running the above code on host2. Please suggest.
Also when i run the above code, it shows information on :
METASTORE_CONNECTION_DRIVER as derby connection embedded driver,
METASTORECONNECTURLKEY as jdbc:mysql://<host name>/<database name>?createDatabaseIfNotExist=true,
METASTORE_CONNECTION_USER_NAME as "APP" and
METASTOREPWD as "mine"
replace this section of your code :
conf.addResource(new Path("/home/hadoop/hive-0.12.0/conf/hive-site.xml"));
Class.forName(conf.getVar(ConfVars.METASTORE_CONNECTION_DRIVER));
conn = DriverManager.getConnection(
conf.getVar(ConfVars.METASTORECONNECTURLKEY),
conf.getVar(ConfVars.METASTORE_CONNECTION_USER_NAME),
conf.getVar(ConfVars.METASTOREPWD));
with the below :
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://host2:3306/metastore", "urusername", "urpassword");
[note :Change the metastore dbname, user and password accordingly as per your setup.]
now :
Statement st = conn.createStatement();
ResultSet rs = st.executeQuery("show tables");
while (rs.next()) {
System.out.println("Tables:" +rs.getString(1));
}
See are you getting the metastore table names or not.

How do I load a xml in Optaplanner

I have created a MySQL database with entries similar to nurse roster, Now i need to send this data to optaplanner deployed on my server. To which file do i need to send it in the optaplanner folder deployed on server to get the results displayed on my webpage.
I'm using Xstream to generate XML file.
Can any one please give me brief on how to make this functionality work and get me the desired results.
The whole dataset serialization from and to XML is part of optaplanner-examples: OptaPlanner itself doesn't provide or require any serialization format. That being said, optaplanner-examples includes the following serialization formats:
Every example: XStream XML format in data directories unsolved and solved. The format is defined by the XStream annotations (#XStreamAlias etc) on the domain classes. In some cases the XML format is too verbose, causing OutOfMemoryError, for example for the big MachineReassignment B datasets.
Most examples: Competition specific TXT format in data directories import and export. The format is defined by the competition (see docs). In the examples GUI, click on button Import to load them.
I suggested you to read the final chapter in optaplanner manual / documentation :
Chapter 15. Integration
If your data source is a database, you can annotate your domain POJO's with JPA annotations. I think it will be a waste if you still store the data from database to xml file then feed the xml file to optaplanner, it will be more wise to feed your POJO objects to optaplanner directly.
I don't know what your web application technology, but the general algorithm will be like this :
Get POJO object data from your database (you can use JPA etc.)
Construct the solution class object
Feed the solution object to optaplanner solver
Get the best solution from optaplanner solver and present it to your user in your user desire.
Take a look at CloudBalancingHelloWorld.java class to get the basic idea. Hope this can help you.
package com.jdbcxml;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import org.w3c.dom.Document;
class EmployeeDAO
{
private Connection conn = null;
static
{
try
{
Class.forName("com.mysql.jdbc.Driver");
}
catch (Exception e)
{
e.printStackTrace();
}
}
public EmployeeDAO()
{
String url = "jdbc:mysql://50.62.23.184:3306/gtuser";
String userId = "gtuser1";
String passWord = "";
try
{
conn = DriverManager.getConnection(url, userId, passWord);
}
catch (SQLException e)
{
e.printStackTrace();
}
}
public void finalize()
{
try
{
conn.close();
}
catch (SQLException e)
{
e.printStackTrace();
}
}
public Document getCustomerList()
{
Document doc = null;
try
{
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * from t7_users");
doc = JDBCUtil.toDocument(rs);
rs.close();
stmt.close();
}
catch (Exception e)
{
e.printStackTrace();
}
return doc;
}
public String getCustomerListAsString()
{
String xml = null;
try
{
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * from t7_users");
xml = JDBCUtil.toXML(rs);
rs.close();
stmt.close();
}
catch (Exception e)
{
e.printStackTrace();
}
return xml;
}
public static void main(String argv[]) throws Exception
{
EmployeeDAO dao = new EmployeeDAO();
String xml = dao.getCustomerListAsString();
System.out.println(xml);
Document doc = dao.getCustomerList();
System.out.println(doc);
//PrintWriter out = new PrintWriter(new FileWriter("output.txt"));
//out.write(doc);;
//out.close();
}
}
Here the pseudo code (I never actually use JSP, I currently using GWT) to give you the basic idea, but please do remember these notes :
I think it will be a waste to save your POJO objects to xml then use XStream library to extract it again to POJO objects. In optaplanner example, they use it because it only need a static data and for the sake of example.
I assume that you already create your approriate domain class model that fit your planning problem domain. Because this is one of the core concept of optaplanner.
In method generateCustomerRoster, you should put your own logic to convert your customer POJO objects to planning solution object.
Hope this can help you and lead you to finish your job. Thanks & Regards.
package com.jdbcxml;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import org.w3c.dom.Document;
public class EmployeeDAO
{
private Connection conn = null;
static
{
try
{
Class.forName("com.mysql.jdbc.Driver");
}
catch (Exception e)
{
e.printStackTrace();
}
}
public EmployeeDAO()
{
String url = "jdbc:mysql://50.62.23.184:3306/gtuser";
String userId = "gtuser1";
String passWord = "";
try
{
conn = DriverManager.getConnection(url, userId, passWord);
}
catch (SQLException e)
{
e.printStackTrace();
}
}
public void finalize()
{
try
{
conn.close();
}
catch (SQLException e)
{
e.printStackTrace();
}
}
public List<Customer> getCustomerList()
{
Document doc = null;
try
{
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * from t7_users");
doc = JDBCUtil.toDocument(rs);
rs.close();
stmt.close();
}
catch (Exception e)
{
e.printStackTrace();
}
return doc;
}
public CustomerRoster generateCustomerRoster(List<Customer> rawData) {
CustomerRoster result = new CustomerRoster();
// here you should write your logic to generate Customer Roster data from your Raw Data (Customer)
return result;
}
public static void main(String argv[]) throws Exception
{
// Build the Solver
SolverFactory solverFactory = SolverFactory.createFromXmlResource("yourSolverConfig.xml");
Solver solver = solverFactory.buildSolver();
// Load your problem
EmployeeDAO dao = new EmployeeDAO();
List<Customer> listCustomer = dao.getCustomerList();
CustomerRoster unsolvedCustomerRoster = generateCustomerRoster(listCustomer);
// Solve the problem
solver.solve(unsolvedCustomerRoster);
CustomerRoster solvedCustomerRoster = (CustomerRoster) solver.getBestSolution();
// Display the result
DataGrid grid = new DataGrid(solvedCustomerRoster); // Just change this line code to display to any of your view component
}
}

Adding a java class file in an another java class file

I am doing a jsp project in which, I have a dbconn.java page in which database connection to MySQL database is created.
I want to call it in an another java page for getting the database connection.
I dont know how to include the page dbconn.java into my page. Please help.
I know its a simple question for you all, but I could not find the answer.
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ActionContext;
import java.util.*;
import java.util.Date;
import java.sql.*;
package com.act;
public class dbconn {
public String execute() throws Exception
{
Connection con=null;
Statement stmt1=null;
Class.forName("com.mysql.jdbc.Driver");
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/mydatabasename", "root", "password");
}
}
This is my dbconn.java page. Is this correct?
You need to return the Connection object from this utility class.
I rewrite your class with name ConnectionManager like this :
import java.sql.*;
public class ConnectionManager{
private Connection con = null;
public Connection getCon(){
try{
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydatabasename","root", "password");
}
catch(Exception e){
e.printStackTrace();
}
return con;
}
}
Now in your other classes, call this class like this whenever you need a db-connection:
Connection con = new ConnectionManager().getCon();
PreparedStatement st = con.prepareStatement("YOUR SQL QUERY");