I am using JTDS to connect to a MS SQL Server. Connection to the database is no problem, but when I try to execute a statement, I get a Database 'java' does not exist exception.
ConnectionString:
conn = DriverManager.getConnection("jdbc:jtds:sqlserver://localhost;DatabaseName=MyDatabase;user=testuser;password=testpassword");
Trying to execute the script:
private void runStatement(String scriptLocation) {
if(scriptLocation == null) {
return;
}
try {
InputStream is = getClass().getClassLoader().getResourceAsStream(scriptLocation);
String query = is.toString();
is.close();
Statement stmt = conn.createStatement();
stmt.executeQuery(query);
} catch(IOException | SQLException ex) {
log.warning(ex.getMessage());
}
}
Stacktrace:
WARNING: Database 'java' does not exist. Make sure that the name is entered correctly.
java.sql.SQLException: Database 'java' does not exist. Make sure that the name is entered correctly.
at net.sourceforge.jtds.jdbc.SQLDiagnostic.addDiagnostic(SQLDiagnostic.java:372)
at net.sourceforge.jtds.jdbc.TdsCore.tdsErrorToken(TdsCore.java:2988)
at net.sourceforge.jtds.jdbc.TdsCore.nextToken(TdsCore.java:2421)
at net.sourceforge.jtds.jdbc.TdsCore.getMoreResults(TdsCore.java:671)
at net.sourceforge.jtds.jdbc.JtdsStatement.executeSQLQuery(JtdsStatement.java:505)
at net.sourceforge.jtds.jdbc.JtdsStatement.executeQuery(JtdsStatement.java:1427)
at com.exampe.MyJTDSConnection.runStatement(MyJTDSConnection.java:238)
at com.exampe.MyJTDSConnection.loadPageTitle(MyJTDSConnection.java:208)
at com.exampe.MyJTDSConnection.runTesting(MyJTDSConnection.java:69)
at com.exampe.SeleniumTesting.runTest(SeleniumTesting.java:59)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
...
As mentioned in the comment to your question, applying the .toString() method to the InputStream object does not read the InputStream. Instead it just returns a String representation of the object itself, not what the object contains.
For example, my Java project has a resource file named "script.sql" that contains:
SELECT ##VERSION
The following code compares the result of simply doing a .toString() on the object vs. using Apache Commons IO to actually read the InputStream into a String:
package resourceTest;
import java.io.InputStream;
import org.apache.commons.io.IOUtils;
public class ResourceTestMain {
public static void main(String[] args) {
try (InputStream is = ResourceTestMain.class.getClassLoader().getResourceAsStream("resources/script.sql")) {
String toStringValue = is.toString();
String contents = IOUtils.toString(is, "UTF-8");
is.close();
System.out.println("is.toString() returned:");
System.out.println(" " + toStringValue);
System.out.println();
System.out.println("IOUtils.toString(is, \"UTF-8\") returned:");
System.out.println(" " + contents);
} catch (Exception e) {
e.printStackTrace(System.out);
}
}
}
The results are:
is.toString() returned:
java.io.BufferedInputStream#804a77
IOUtils.toString(is, "UTF-8") returned:
SELECT ##VERSION
Related
Unable to use copy command with jdbc Postgres. Whats wrong with the below code snippet sample.
public boolean loadReportToDB(String date) {
// TODO Auto-generated method stub
Connection connection = DBUtil.getConnection("POSTGRESS");
String fileName = "C:/_0STUFF/NSE_DATA/nseoi_" + date + ".csv";
String sql = "\\copy fno_oi FROM 'C:\\_0STUFF\\NSE_DATA\\nseoi_27102017.csv' DELIMITER ',' CSV header";
try {
PreparedStatement ps = connection.prepareStatement(sql);
System.out.println("query"+ps.toString());
int rowsaffected = ps.executeUpdate();
System.out.println("INT+" + rowsaffected);
return true;
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return false;
}
org.postgresql.util.PSQLException: ERROR: syntax error at or near "\"
Position: 1
at org.
if we use
String sql = "copy fno_oi FROM 'C:\\_0STUFF\\NSE_DATA\\nseoi_27102017.csv' DELIMITER ',' CSV header";
then no rows are updated
postgres version postgresql-10.0-1-windows-x64
This works for me:
try (Connection conn = DriverManager.getConnection(connUrl, myUid, myPwd)) {
long rowsInserted = new CopyManager((BaseConnection) conn)
.copyIn(
"COPY table1 FROM STDIN (FORMAT csv, HEADER)",
new BufferedReader(new FileReader("C:/Users/gord/Desktop/testdata.csv"))
);
System.out.printf("%d row(s) inserted%n", rowsInserted);
}
Using copyIn(String sql, Reader from) has the advantage of avoiding issues where the PostgreSQL server process is unable to read the file directly, either because it lacks permissions (like reading files on my Desktop) or because the file is not local to the machine where the PostgreSQL server is running.
As your input file is stored locally on the computer running your Java program you need to use the equivalent of copy ... from stdin in JDBC because copy can only access files on the server (where Postgres is running).
To do that use the CopyManager API provided by the JDBC driver.
Something along the lines:
Connection connection = DBUtil.getConnection("POSTGRES");
String fileName = "C:/_0STUFF/NSE_DATA/nseoi_" + date + ".csv";
String sql = "copy fno_oi FROM stdin DELIMITER ',' CSV header";
BaseConnection pgcon = (BaseConnection)conection;
CopyManager mgr = new CopyManager(pgcon);
try {
Reader in = new BufferedReader(new FileReader(new File(fileName)));
long rowsaffected = mgr.copyIn(sql, in);
System.out.println("Rows copied: " + rowsaffected);
} catch (SQLException e) {
e.printStackTrace();
}
Unable to use copy command with jdbc Postgres. Whats wrong with the below code snippet sample.
public boolean loadReportToDB(String date) {
// TODO Auto-generated method stub
Connection connection = DBUtil.getConnection("POSTGRESS");
String fileName = "C:/_0STUFF/NSE_DATA/nseoi_" + date + ".csv";
String sql = "\\copy fno_oi FROM 'C:\\_0STUFF\\NSE_DATA\\nseoi_27102017.csv' DELIMITER ',' CSV header";
try {
PreparedStatement ps = connection.prepareStatement(sql);
System.out.println("query"+ps.toString());
int rowsaffected = ps.executeUpdate();
System.out.println("INT+" + rowsaffected);
return true;
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return false;
}
org.postgresql.util.PSQLException: ERROR: syntax error at or near "\"
Position: 1
at org.
if we use
String sql = "copy fno_oi FROM 'C:\\_0STUFF\\NSE_DATA\\nseoi_27102017.csv' DELIMITER ',' CSV header";
then no rows are updated
postgres version postgresql-10.0-1-windows-x64
This works for me:
try (Connection conn = DriverManager.getConnection(connUrl, myUid, myPwd)) {
long rowsInserted = new CopyManager((BaseConnection) conn)
.copyIn(
"COPY table1 FROM STDIN (FORMAT csv, HEADER)",
new BufferedReader(new FileReader("C:/Users/gord/Desktop/testdata.csv"))
);
System.out.printf("%d row(s) inserted%n", rowsInserted);
}
Using copyIn(String sql, Reader from) has the advantage of avoiding issues where the PostgreSQL server process is unable to read the file directly, either because it lacks permissions (like reading files on my Desktop) or because the file is not local to the machine where the PostgreSQL server is running.
As your input file is stored locally on the computer running your Java program you need to use the equivalent of copy ... from stdin in JDBC because copy can only access files on the server (where Postgres is running).
To do that use the CopyManager API provided by the JDBC driver.
Something along the lines:
Connection connection = DBUtil.getConnection("POSTGRES");
String fileName = "C:/_0STUFF/NSE_DATA/nseoi_" + date + ".csv";
String sql = "copy fno_oi FROM stdin DELIMITER ',' CSV header";
BaseConnection pgcon = (BaseConnection)conection;
CopyManager mgr = new CopyManager(pgcon);
try {
Reader in = new BufferedReader(new FileReader(new File(fileName)));
long rowsaffected = mgr.copyIn(sql, in);
System.out.println("Rows copied: " + rowsaffected);
} catch (SQLException e) {
e.printStackTrace();
}
I want to access MySQL database within my MapReduce program. I have a DBConnection class and I getConnection within the mapper class.The db.properties file is in place and with correct path mentioned in the DBConnection class.
Everytime I run the hadoop jar command I get error java.io.FileNotFoundException: db.properties (No such file or directory).
How can I resolve this?
Establishing DB connection in mapper:
Connection con = DBConnection.getConnection();
PreparedStatement pst = null;
String selectRows = "Select count(*) from sample";
Thanks
Try with this:
Prior Java 1.7:
InputStream input = YourClassName.class.getResourceAsStream("/db.properties");
try {
prop.load(input);
} catch (IOException ex) {
}finally{
input.close();
}
Java 1.7 and ahead:
try (InputStream input = YourClassName.class.getResourceAsStream("/db.properties")) {
prop.load(input);
} catch (IOException ex) {
}
I am using the JDBC driver to connect to a mysql database and using the "LOAD DATA INFILE" command in my java application to load(insert) a text file into the database. I am getting the following error: Data truncation: Data too long for column xxx at row 1.
However if I load the same text file manually by logging into the database and entering the SQL manually, the data loads fine.
Can someone pelase tell me what the error might be?
I am running this on Red Hat Enterprise Linux Server release 5.8 and the jdk version is 1.5.0_16 if that helps
This is the function used to load the data
public static void loaddata(Connection conn, String filename, String tablename)
{
try{
Statement stmt = null;
stmt = conn.createStatement();
File file = new File(filename);
file.getAbsolutePath().replace("\\", "\\\\");
String cmd = "LOAD DATA INFILE '"
+ file.getAbsolutePath().replace("\\", "\\\\")
+ "' INTO TABLE " + tablename + " FIELDS TERMINATED BY \'^\'";
stmt.executeUpdate(cmd);
System.out.println("cmd :" + cmd);
}
catch(SQLException sqle){
sqle.printStackTrace();
}
}
This is the function to create the JDBC connection:
public static Connection createConnection()
{
Connection conn=null;
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
}
catch(Exception e) {
e.printStackTrace();
}
try {
String url = ""; //URL mentioned in the actual code
conn = DriverManager.getConnection(url, user, pass);
} catch (SQLException sqe1) {
sqe1.printStackTrace();
}
return conn;
}
I'm trying to hit a stored procedure but I'm getting this error message: 'javax.ejb.EJBException'... I've never worked with stored procedures so the exception is a bit Greek to me.
Anyone that could perhaps shed some light on this? Below I pasted the code that I wrote:
#WebMethod(operationName = "getSpecimenResultsXml")
public String getSpecimenResultsXml(#WebParam(name = "specimenGuid") String specimenGuid, #WebParam(name = "publicationGuid") String publicationGuid, #WebParam(name = "forProvider") String forProvider) {
//Method variables
ResultSet rs = null;
String xml = null;
// 1) get server connection
Connection conn = dataBaseConnection.getConnection();
// 2) Pass recieved parameters to stored proc.
try {
CallableStatement proc =
conn.prepareCall("{ call getSpecimenReportXml(?, ?, ?) }");
proc.setString(1, specimenGuid);
proc.setString(2, publicationGuid);
proc.setString(3, forProvider);
proc.execute();
rs = proc.getResultSet();
} catch (SQLException e) {
System.out.println("--------------Error in getSpecimenResultsXml------------");
System.out.println("Cannot call stored proc: " + e);
System.out.println("--------------------------------------------------------");
}
// 3) Get String from result set
try {
xml = rs.getString(1);
} catch (SQLException e) {
System.out.println("--------------Error in getSpecimenResultsXml------------");
System.out.println("Cannot retrieve result set: " + e);
System.out.println("--------------------------------------------------------");
}
// 4) close connection
try {
conn.close();
} catch (Exception e) {
System.out.println("--------------Error in getSpecimenResultsXml------------");
System.out.println("Cannot close connection: " + e);
System.out.println("--------------------------------------------------------");
}
// 5) return the returned String
return xml;
}
Oh and the stored procedure us called getSpecimenReportXml...
Your exception would say 'caused by' somewhere - which is a big clue. If it's an NPE then you might want to check the values of dataBaseConnection and conn to make sure they've been set. Use a debugger to do this, but the exception should tell you exactly which line caused the problem.