gurus,
I am new to Java SQL, and need some help.
I'm trying to get a parameter from MS SQL Server 2008. The data is definitely there - it is a current and valid DB, and I'm trying to use the users records to get cridentials for another application.
I asserted the following query:
String query = "SELECT [USER].qc_number FROM [USER] WHERE "[USER].login_name = '"
+ userNameInput + "' AND [USER].password = '" + passWordInput + "';";
Where userNameInput and passWordInput are received from the user. The URL, query and driver class are definitely correct: I checked the DB schema both from the application and from the server views. Furthermore, I verified all the Exceptions systems by changing parameters one by one, resulting in correct Exceptions messages. However, I get a resultSet with 1 column and 0 rows.
The code is below:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class trOdbc
{// database URL
final String DB_URL = "***";
final String Class_URL = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
private Connection connection = null; // manages connection
private Statement statement = null; // query statement
private ResultSet resultSet = null; // manages results
private Boolean connectedToDatabase = false;
// ----------------------------------------------------------
public void createJdbcConnection()
{ // connect to database books and query database
if (connectedToDatabase)
{ return; }
try
{ // connectedToDatabase is false - establish the connection
Class.forName(Class_URL);
connection = DriverManager.getConnection
(DB_URL, "***", "***" );
statement = connection.createStatement
(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
connectedToDatabase = true;
}
catch (SQLException ex)
{ System.out.println ("SQL Exception in connection establishment: " + ex); }
catch (ClassNotFoundException ex)
{ System.out.println ("Class not found exception in query process: " + ex); }
}
// ----------------------------------------------------------
public String [][] processJdbcQuery (String query)
{
createJdbcConnection ();
if (!connectedToDatabase)
{ return null; }// the connection wasn't established
try
{// query database
resultSet = statement.executeQuery(query);
int columns = resultSet.getMetaData().getColumnCount();
int rows = 0;
if (resultSet != null)
{
resultSet.beforeFirst();
resultSet.last();
rows = resultSet.getRow();
}
String [][] tempData = new String[rows][columns];
resultSet.beforeFirst();
rows = 0;
while (resultSet.next())
{
for (int x = 1; x <= columns; x++)
{
tempData [rows][x - 1] = resultSet.getString (x);
}
rows++;
}
CloseJdbcConnection ();
return tempData;
}
catch (SQLException ex)
{
System.out.println ("SQL Exception in query process: " + ex);
CloseJdbcConnection ();
return null;
}
} // end processJdbcQuery
// ----------------------------------------------------------
public void CloseJdbcConnection()
{
if ( connectedToDatabase )
{// close Statement and Connection. resultSet is closed automatically.
try
{
statement.close();
connection.close();
connectedToDatabase = false;
}
catch (SQLException ex)
{ System.out.println ("SQL Exception in connection closure: " + ex); }
} // end if
} // end method CloseJdbcConnection
} // end class trOdbc
Why don't you use Prepared Statement instead ?
Here is a good tutorial for using prepared statement in java
In your case it would be :
String query = "SELECT [USER].qc_number FROM [USER] " +
"WHERE [USER].login_name = ? AND [USER].password = ?;";
And then set it with different values each time you execute it like :
PreparedStatement ps = connection.prepareStatement(query);
ps.setString(1, userNameInput);
ps.setString(2, passWordInput);
resultSet = ps.executeQuery();
Related
I have code, where I have single quote or APOSTROPHE in my search
I have database which is having test table and in name column of value is "my'test"
When running
SELECT * from test WHERE name = 'my''test';
this works fine
If I use the same in a Java program I am not getting any error or any result
But If I give the name with only single quote then it works
SELECT * from test WHERE name = 'my'test';
Could you please help me out to understand.
Java code is
Connection con = null;
PreparedStatement prSt = null;
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
con = DriverManager.
getConnection("jdbc:oracle:thin:#localhost:1521:orcl"
,"user","pwd");
String query = "SELECT * from "
+ "WHERE name = ? ";
prSt = con.prepareStatement(query);
String value = "my'mobile";
char content[] = new char[value.length()];
value.getChars(0, value.length(), content, 0);
StringBuffer result = new StringBuffer(content.length + 50);
for (int i = 0; i < content.length; i++) {
if (content[i] == '\'')
{
result.append("\'");
result.append("\'");
}
else
{
result.append(content[i]);
}
}
prSt.setObject(1, result.toString());
int count = prSt.executeUpdate();
System.out.println("===============> "+count);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} finally{
try{
if(prSt != null) prSt.close();
if(con != null) con.close();
} catch(Exception ex){}
}
You don't have to escape anything for the parameter of a PreparedStatement
Just use:
prSt = con.prepareStatement(query);
prSt.setString("my'mobile");
Additionally: if you are using a SELECT statement to retrieve data, you need to use executeQuery() not executeUpdate()
ResultSet rs = prst.executeQuery();
while (rs.next())
{
// process the result here
}
You might want to go through the JDBC tutorial before you continue with your project: http://docs.oracle.com/javase/tutorial/jdbc/index.html
I create this code for get column name in sql databases. But now I ant to modify above code for get all table data with column name. Then get all data and convert to jsonarray and pass. How I modify this code for get all table data with column name.
#Override
public JSONArray getarray(String sheetName) {
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = (Connection) DriverManager.getConnection("jdbc:mysql://localhost/test", "root", "");
con.setAutoCommit(false);
PreparedStatement pstm = null;
Statement stmt = null;
//-----------------------Drop earliye table -------------------------------------------------------------
try {
String sqldrop = "select COLUMN_NAME from information_schema.COLUMNS where TABLE_NAME='" + sheetName.replaceAll(" ", "_") + "'";
System.out.println(sqldrop);
PreparedStatement mypstmt = con.prepareStatement(sqldrop);
ResultSet resultSet = mypstmt.executeQuery();
JSONArray jsonArray = new JSONArray();
while (resultSet.next()) {
int total_rows = resultSet.getMetaData().getColumnCount();
JSONObject obj = new JSONObject();
for (int i = 0; i < total_rows; i++) {
String columnName = resultSet.getMetaData().getColumnLabel(i + 1).toLowerCase();
Object columnValue = resultSet.getObject(i + 1).toString().replaceAll("_", " ");
// if value in DB is null, then we set it to default value
if (columnValue == null) {
columnValue = "null";
}
/*
Next if block is a hack. In case when in db we have values like price and price1 there's a bug in jdbc -
both this names are getting stored as price in ResulSet. Therefore when we store second column value,
we overwrite original value of price. To avoid that, i simply add 1 to be consistent with DB.
*/
if (obj.has(columnName)) {
columnName += "1";
}
obj.put(columnName, columnValue);
}
jsonArray.put(obj);
}
mypstmt.close();
con.commit();
return jsonArray;
} catch (Exception e) {
System.out.println("There is no exist earlyer databases table!..... :( :( :( **************** " + sheetName.replaceAll(" ", "_"));
}
//----------------------------------------------------------------------------
} catch (ClassNotFoundException e) {
System.out.println(e);
} catch (SQLException ex) {
Logger.getLogger(PassArrayDaoImpl.class.getName()).log(Level.SEVERE, null, ex);
}
System.out.println("%%%%%%%%%%");
return null;
}
My target is get all data with column name and above data pass html page as a json. So if you have any method for get all data with column name is suitable for me.
// code starts here
// This method retrieves all data from a mysql table...
public void retrieveAllData( String host, String user, String pass, String query) {
JTextArea textArea = new JTextArea();
try(
Connection connection = DriverManager.getConnection( host, user, pass )
Statement statement = connection.createStatement()
ResultSet resultSet = statement.executeQuery(query)) {
ResultSetMetaData metaData = resultSet.getMetaData();
int totalColumns = metaData.getColumnCount();
for( int i = 1; i <= totalColumns; i++ ) {
textArea.append( String.format( "%-8s\t", metaData.getColumnName(i) ) );
}
textArea.append( "\n" );
while( resultSet.next() ) {
for( int i = 1; i <= totalColumns; i++ ) {
Object object = resultSet.getObject(i).toString();
textArea.append( String.format("%-8s\t", object) );
}
textArea.append( "\n" );
}
}
}
so i found this code on the internet, basically what supposedly it can do is backup all the tables from a db, my question is on this line:
res = st.executeQuery("select * from xcms." + tableName);
i get the following excpetion exception: SQLException information
what does xcms. stands for? what else can i put here?
res = st.executeQuery("select * from " + tableName);
btw if i erase xcms. and put it like this ^, i can save only the first table not all the tables, thx
the sourcecode webpage:
https://gauravmutreja.wordpress.com/2011/10/13/exporting-your-database-to-csv-file-in-java/#comment-210
public static void main(String[] args) {
Connection con = null;
String url = "jdbc:mysql://localhost:3306/";
String db = "gg";
String driver = "com.mysql.jdbc.Driver";
String user = "root";
String pass = "";
FileWriter fw;
try {
Class.forName(driver);
con = DriverManager.getConnection(url + db, user, pass);
Statement st = con.createStatement();
ResultSet res = st.executeQuery("SELECT table_name FROM INFORMATION_SCHEMA.TABLES WHERE table_schema = 'gg'");
List<String> tableNameList = new ArrayList<String>();
while (res.next()) {
tableNameList.add(res.getString(1));
}
String filename = "C:\\Users\\Angel Silva\\Documents";
for (String tableName : tableNameList) {
int k = 0;
int j = 1;
System.out.println(tableName);
List<String> columnsNameList = new ArrayList<String>();
res = st.executeQuery("select * from " + tableName);
int columnCount = getColumnCount(res);
try {
fw = new FileWriter("C:\\Users\\Angel Silva\\Documents\\popo1121.csv");
for (int i = 1; i <= columnCount; i++) {
fw.append(res.getMetaData().getColumnName(i));
fw.append(",");
}
fw.append(System.getProperty("line.separator"));
while (res.next()) {
for (int i = 1; i <= columnCount; i++) {
if (res.getObject(i) != null) {
String data = res.getObject(i).toString();
fw.append(data);
fw.append(",");
} else {
String data = "null";
fw.append(data);
fw.append(",");
}
}
fw.append(System.getProperty("line.separator"));
}
fw.flush();
fw.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
con.close();
} catch (ClassNotFoundException cnfe) {
System.err.println("Could not load JDBC driver");
cnfe.printStackTrace();
}catch (SQLException sqle) {System.err.println("SQLException information");}
}
public static int getRowCount(ResultSet res) throws SQLException {
res.last();
int numberOfRows = res.getRow();
res.beforeFirst();
return numberOfRows;
}
public static int getColumnCount(ResultSet res) throws SQLException {
return res.getMetaData().getColumnCount();
}
}
This is what I used:
public void sqlToCSV (String query, String filename){
log.info("creating csv file: " + filename);
try {
FileWriter fw = new FileWriter(filename + ".csv");
if(conn.isClosed()) st = conn.createStatement();
ResultSet rs = st.executeQuery(query);
int cols = rs.getMetaData().getColumnCount();
for(int i = 1; i <= cols; i ++){
fw.append(rs.getMetaData().getColumnLabel(i));
if(i < cols) fw.append(',');
else fw.append('\n');
}
while (rs.next()) {
for(int i = 1; i <= cols; i ++){
fw.append(rs.getString(i));
if(i < cols) fw.append(',');
}
fw.append('\n');
}
fw.flush();
fw.close();
log.info("CSV File is created successfully.");
conn.close();
} catch (Exception e) {
log.fatal(e);
}
}
The xms stands for the Database name, in your Connection in the java program you already are establishing the connection to the Database:
(DriverManager.getConnection(url + db, user, pass);
The string db is the name of the DB to connect to.
So no need to have the xms. .just for example use this query:
"SELECT * FROM "+tableName+";"
This is executed in the database you are connected to, for example ggin your code.
For writting the CSV file chillyfacts.com/export-mysql-table-csv-file-using-java/ may help!
SELECT * FROM <MENTION_TABLE_NAME_HERE> INTO OUTFILE <FILE_NAME> FIELDS TERMINATED BY ',';
Example :
SELECT * FROM topic INTO OUTFILE 'D:\5.csv' FIELDS TERMINATED BY ',';
use opencsv dependency to export SQL data to CSV using minimal lines of code.
import com.opencsv.CSVWriter;
import java.io.FileWriter;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class CsvWriter {
public static void main(String[] args) throws Exception {
CSVWriter writer = new CSVWriter(new FileWriter("filename.csv"), '\t');
Boolean includeHeaders = true;
Statement statement = null;
ResultSet myResultSet = null;
Connection connection = null;
try {
connection = //make database connection here
if (connection != null) {
statement = connection.createStatement();
myResultSet = statement.executeQuery("your sql query goes here");
writer.writeAll(myResultSet, includeHeaders);
}
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
I currently have a very large file which contains a few million lines of entries, and want them inserted into a database. The connection established from java to SQL works as I have tried inserting the data singularly and it works, however, when I switched to using executeBatch and addBatch, it seems to loop though but not populating anything into my database.
Code is as follows:
import java.io.BufferedReader;
import java.io.FileReader;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.SQLException;
public class fedOrganiser6 {
private static String directory = "C:\\Users\\x\\Desktop\\Files\\";
private static String file = "combined.fed";
private static String mapperValue = "";
public static void main(String[] args) throws Exception {
Connection conn = null;
try {
BufferedReader mapper = new BufferedReader(new FileReader(directory + file));
String dbURL = "jdbc:sqlserver://localhost\\SQLExpress;database=TIMESTAMP_ORGANISER;integratedSecurity=true";
String user = "sa";
String pass = "password";
conn = DriverManager.getConnection(dbURL, user, pass);
if (conn != null) {
DatabaseMetaData dm = (DatabaseMetaData) conn.getMetaData();
System.out.println("Driver name: " + dm.getDriverName());
System.out.println("Driver version: " + dm.getDriverVersion());
System.out.println("Product name: " + dm.getDatabaseProductName());
System.out.println("Product version: " + dm.getDatabaseProductVersion());
System.out.println("clearing database");
conn.createStatement().executeUpdate("truncate table TimestampsStorage");
System.out.println("bulk insert into database");
System.out.println("complete");
int i = 0;
int records = 0;
String query = "INSERT INTO TimestampsStorage " + "values(" + "'" + mapperValue.toString() + "'"+ ")";
conn.prepareStatement(query);
for (mapperValue = mapper.readLine(); mapperValue != null; mapperValue = mapper.readLine()) {
i++;
records++;
System.out.println("Batching " + records + " records...");
conn.createStatement().addBatch(query);
if (i == 100000) {
conn.createStatement().executeBatch();
i = 0;
}
}
}
conn.createStatement().executeBatch();
conn.createStatement().close();
System.out.print("Done");
} catch (SQLException ex) {
ex.printStackTrace();
} finally {
try {
if (conn != null && !conn.isClosed()) {
conn.close();
}
} catch (SQLException ex) {
ex.printStackTrace();
}
}
}
}
createStatement() creates a new statement object, so you're execute a different statement than the one you're batching on. You should create the PreparedStatement once, add several batches to it, and then execute on the same object:
String query = "INSERT INTO TimestampsStorage VALUES (?)";
PreparedStatement ps = conn.prepareStatement(query);
for (mapperValue = mapper.readLine();
mapperValue != null;
mapperValue = mapper.readLine()) {
i++;
records++;
System.out.println("Batching " + records + " records...");
ps.setString(1, mapperValue);
ps.addBatch();
if (i == 100000) {
ps.executeBatch();
i = 0;
}
}
I think you are a bit mistaken on how batch processing for JDBC works.
You are creating a new Statement each time you call conn.createStatement().
Instead, you will want to use a PreparedStatement. First, change your query to include a ? where you want your values to go.
String query = "INSERT INTO TimestampsStorage VALUES(?)";
Then, when you call conn.prepareStatement(query), store the returned PreparedStatement.
PreparedStatement ps = conn.prepareStatement(query);
This PreparedStatement will then 'remember' your query, and you can simply change the values you want where the ? is on each iteration of your loop.
ps.setString(1, mapperValue);
The setString method will take your mapperValue and use it instead of the first ? it finds in your query (since you pass in the index 1).
Then, instead of calling conn.createStatement().addBatch(), you would call ps.addBatch().
Then, outside of your loop, you can call ps.executeBatch(). (There is no need to call this inside your loop, so you can remove your if (i == 100000) condition).
Finally, if you are using Java 7+, you can use a try with resources, so that you don't need to worry about closing the PreparedStatement or Connection in a finally block.
Here is what your end result should look like.
String query = "INSERT INTO TimestampsStorage VALUES (?)";
try (Connection con = DriverManager.getConnection(dbURL, user, pass); PreparedStatement ps = con.prepareStatement(query);) {
for (mapperValue = mapper.readLine(); mapperValue != null; mapperValue = mapper.readLine()) {
records++;
ps.setString(1, mapperValue);
ps.addBatch();
}
System.out.println("Executing batch of " + records + " records...");
ps.executeBatch();
} catch (SQLException ex) {
//handle exception
}
you are throwing away the prepared statement
String query = "INSERT INTO TimestampsStorage VALUES (?)";
PreparedStatement statement = conn.prepareStatement(query);
for (mapperValue = mapper.readLine(); mapperValue != null; mapperValue = mapper.readLine()) {
i++;
records++;
System.out.println("Batching " + records + " records...");
statement.setString(1,mapperValue);
statement.addBatch();
if (i == 100000) {
statement.executeBatch();
i = 0;
}
I'm using phpmy admin and I need to Display "Not Found" message in case searching element is not found in the DB.
Used code is here.
Connection c = DBconnect.connect();
Statement s = c.createStatement();
String e = txtempId.getText();
ResultSet rs = s.executeQuery("SELECT * FROM nonacademic WHERE empId='" +e+ "'");
I used this method to search empId ,if empId is not available in db I need to display a message.Please give me a solution how to detect, if empId is not available in DB.
if (rs != null)
{
out.println("result set has got something");
while (rs.next())
{
//I am processing result set now
}
}
else
{
out.println("Not Found");
}
Use if statement like this
Connection c = DBconnect.connect();
Statement s = c.createStatement();
String e = txtempId.getText();
ResultSet rs = s.executeQuery("SELECT * FROM nonacademic WHERE empId='" +e+ "'");
if(rs.next())
{
do
{
// If there is data, then process it
}
while(rs.next());
}
else
System.out.println("Not Found");
Added parse of text to integer, assuming empId is an integer.
int empId = Integer.parseInt(txtempId.getText());
try (Connection c = DBconnect.connect()) {
String sql = "SELECT *" +
" FROM nonacademic" +
" WHERE empId = ?";
try (Statement s = c.prepareStatement(sql)) {
s.setInt(1, empId);
try (ResultSet rs = s.executeQuery()) {
if (! rs.next()) {
// not found
} else {
// found, call rs.getXxx(...) to get values
}
}
}
}
Just use the basic simple if & else statement. If the ResultSet is "null" or it doesn't contain any record display the Message otherwise read data & display.
Connection c = DBconnect.connect();
Statement s = c.createStatement();
String e = txtempId.getText();
ResultSet rs = s.executeQuery("SELECT * FROM nonacademic WHERE empId='" +e+ "'");
if(rs.next())
// record found do the processing
else
System.out.println("Not Found");
String e = txtempId.getText();
String sql="select *from nonacademic where empId='"+ e+"' ";
try {
boolean status=DatabaseConnection.checkValue(sql);
if (status) {
JOptionPane.showMessageDialog(null,
"This id is available");
} else {
JOptionPane.showMessageDialog(null,
"Not found");
}
} catch (Exception e) {
}
This method return check whether the search element is exist or not
public static boolean checkValue(String sql) throws Exception {
boolean b = false;
ResultSet rst = null;
Statement st = getStatement();
rst = st.executeQuery(sql);
if (rst.next()) {
b = true;
}
return b;
}