I have a basic java application and a sqlite DB.
I can create table manually through sqLite browser. And I am able to access these tables from my JAVA application.
E.g. Reading from existing table: (I have omitted the try catch blocks in the sample below just to reduce the length of question)
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
String query = "select * from test1 where uname = ? and name = user1";
preparedStatement = connection.prepareStatement(query);
preparedStatement.setString(1, "test");
resultSet = preparedStatement.executeQuery();
if(resultSet.next())
return true;
else
return false;
I am able to perform this query successfully.
However, if I create / modify a table, changes does not show up in SQlite DB (I am viewing db in sqLite browser). If I copy paste the same query in SQlite browser, the query runs successfully and a row is added.
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
String query = "INSERT INTO COMPANY (ID,NAME,AGE) VALUES (3, 'tOM', 32);";
preparedStatement = connection.prepareStatement(query);
preparedStatement.executeUpdate();
Am I missing something?
EDIT: Both the above tables exist in my sqlite db. Both were created through sqlite browser
EDIT2: I was getting true from my example 1 above, that's why I felt that I am able to read from db. I update my code to print the data read and nothing gets printed which means I am not able to read the data as well:
resultSet = preparedStatement.executeQuery("SELECT * FROM test1");
and
private static void outputResultSet(ResultSet rs) throws Exception {
ResultSetMetaData rsMetaData = rs.getMetaData();
int numberOfColumns = rsMetaData.getColumnCount();
for (int i = 1; i < numberOfColumns + 1; i++) {
String columnName = rsMetaData.getColumnName(i);
System.out.print(columnName + " ");
}
System.out.println();
System.out.println("----------------------");
while (rs.next()) {
for (int i = 1; i < numberOfColumns + 1; i++) {
System.out.print(rs.getString(i) + " ");
}
System.out.println();
}
}
The connection string is:
Class.forName("org.sqlite.JDBC");
Connection conn = DriverManager.getConnection("jdbc:sqlite:C:\\Users\\akshay\\sqlite_test.sqlite");
conn.setAutoCommit(true);
return conn;
Related
I need to verify if a column already exists in a table . My class extends CustomTaskChange so my method receives a Database object as an argument. Can I make the verification I want trough the ResultSetObject?
#Override
public void execute(Database database) throws CustomChangeException {
JdbcConnection connection = (JdbcConnection) database.getConnection();
DatabaseMetaData metadata;
metadata = connection.getMetaData();
String[] types = {"TABLE"};
ResultSet rs = metadata.getTables(null, null, "%", types);
Statement s = connection.createStatement();
while (rs.next()) {
String tableName = rs.getString(3);
if (tableName.endsWith(this.suffix)) {
String sql = sqlStatement.replaceAll("name", tableName);
s.execute(sql);
}
}
}
Basically what this piece of code is doing is going through all the tables in my database. If, a table name ends in a suffix, I will add the column to it. This way I can add a column to multiple tables at the same time.
But I want to add another verification to add the column to a table, and that is that there can't already be a column with that name in that table. Something like this(pseudocode)
if(tableName.endsWith(this.suffis) && columnName doesn't exist in that table){
String sql = sqlStatement.replaceAll("name", tableName);
s.execute(sql);
}
you can fetch columns from each of the tables then you can check column exist or not.
{
Statement st = con.createStatement();
ResultSet rs = st.executeQuery("SELECT * FROM TABLENAME LIMIT 1");
ResultSetMetaData md = rs.getMetaData();
int col = md.getColumnCount();
for (int i = 1; i <= col; i++){
String col_name = md.getColumnName(i);
if(col_name.equals("YourColumnName"){
/*Then the column already exist*/
}}
With the above code, you can check the metadata and then execute the SQL query to delete the same.
this is my code where I get the problem, following directly from a recorded lecture of mine to catch up on, he has no errors next to his line but I do? Curious as to what I'm doing wrong as I am directly copying the code off the screen.
'''
public class DisplayAuthors {
// database URL
static final String DATABASE_URL = "jdbc:mysql://localhost/books";
public static void main ( String args[] ) {
Connection connection = null;
Statement pstat = null;
ResultSet resultSet = null;
try {
// establish connection to database
connection = DriverManager.getConnection(DATABASE_URL, "root", "");
// create Prepared Statement for querying table
pstat = connection.prepareStatement("SELECT AuthorID, FirstName, LastName FROM Authors");
// query database
resultSet = pstat.executeQuery();
//process query results
ResultSetMetaData metaData = resultSet.getMetaData();
int numberOfColumns = metaData.getColumnCount();
System.out.println(" Authors Table of Books Database:\n");
for (int i = 1; i <= numberOfColumns; i++ )
System.out.print(metaData.getColumnName( i )+ "\t");
System.out.println();
'''
Statement doesn't have an executeQuery() method, it only has executeQuery(String) - this is what the error is telling you.
PreparedStatement does have executeQuery() but you defined pstat as a Statement instead of PreparedStatement. Change
Statement pstat = ...
to
PreparedStatement pstat = ...
I want to execute the following query in java, through mysql jdbc: SELECT COUNT (*) FROM ORDERS, CUSTOMER WHERE O_ORDEYKEY = O_CUSTKEY
I have this code:
Connection conn = new DatabaseConnection().createMySQLConnection();
int totalRows=0;
for(int j=0;j<tables.size();j++)
{
Statement stmt = null;
ResultSet rs = null;
int rowCount = -1;
try {
conn.setAutoCommit(false);
stmt = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
rs = stmt.executeQuery("SELECT COUNT(*) FROM " + tables.get(j)
+ " WHERE O_ORDERKEY = O_CUSTKEY;");
rs.next();
rowCount = rs.getInt(1);
totalRows= totalRows+rowCount;
} finally {
rs.close();
stmt.close();
}
}
But I wanted to run it faster. How can I do this ?
For easier reading you should avoid the old implicit join syntax based on where and use the SQL standard (since 1992) explicit join syntax:
SELECT COUNT (*)
FROM ORDERS
INNER JOIN CUSTOMER ON ORDERS.O_ORDEYKEY = CUSTOMER.O_CUSTKEY
For better performance be sure you have an index on:
table ORDERS column O_ORDEYKEY
table CUSTOMER column O_CUSTKEY
try{
Class.forName("com.mysql.jdbc.Driver");
System.out.println("Connecting to a selected database...");
conn = DriverManager.getConnection(DB_URL, USER, PASS);
System.out.println("Connected database successfully...");
System.out.println("Inserting records into the table...");
stmt = conn.createStatement();
for (int j = 0; j < 30; j++)
{
int a = 230 + j % 15;
String String = Integer.toString(a);
String str = Integer.toString(a);
double b = 1.3 + j % 17 * 0.1;
String aString = Double.toString(b);
String IKW2 = String.valueOf(b);
String sql ="INSERT INTO cmd";
sql +="VALUES" + "("+ a +b ")";
stmt.executeUpdate(sql);
}
catch(SQLException se){
se.printStackTrace();
}
Here i have done jdbc connection and want to import data
into mysql. So used insert statement .In stack trace its
showing that the connection is done bt there is syntaxerrorexception.
i want to generate data and then want to print all the data to import
in db. Is my insert query is wrong??
You shall use Prepared Statements. Following steps shall help you.
Pre calculate all your column values a, b,c etc.
Create a Prepared Statement (assuming three columns in table)
PreparedStatement ps = con.prepareStatement("INSERT INTO CMD VALUES(?,?,?)");
set parameter values using PreparedStatement#setXXX methods
execute prepared statement
I have a sql query fro which I need the column name and data type and it's table name and schema name:
Thsi is the method I am using for using and testing it for SQLSERVER:
public static void getMetadataForConn(Connection conn) throws SQLException
{
ResultSet rs = null;
try
{
Statement stmt = conn.createStatement();
rs = stmt.executeQuery("SELECT AB_DEMO_SRC.dbo.employee.dept_id dept_id, AB_DEMO_SRC.dbo.employee.email_add email_add, AB_DEMO_SRC.dbo.employee.emp_address emp_address, AB_DEMO_SRC.dbo.employee.emp_id emp_id, AB_DEMO_SRC.dbo.employee.emp_name emp_name FROM AB_DEMO_SRC.dbo.employee ");
ResultSetMetaData md = rs.getMetaData();
int columnCount = md.getColumnCount();
for (int i = 1; i <= columnCount; i++)
System.out.print(md.getColumnName(i) + "(" + md.getColumnType(i) + ") "+md.getSchemaName(i)+"."+md.getTableName(i));
System.out.println();
while (rs.next())
{
for (int i = 1; i <= columnCount; i++)
{
Object o = rs.getObject(i);
System.out.print(null == o ? "" : o.toString() + " ");
}
System.out.println();
}
}
finally
{
if (null != rs)
{
rs.close();
}
}
}
I get all the other metadata details like data type, precision and scale..Strangely, I am getting tablename and schema name as "" that is blank..IS there any other way to fetch the metadata of the columns present in a Query?
I think the problem is that the columns of a ResultSet are not related to any table, they are related just to the query. The query could be complex, it could have computed columns etc. That is why their table names are blank.
If you want to get the information about the columns of a specific table, you can use the metadata of the database:
DatabaseMetaData meta = conn.getMetaData();
ResultSet columns = meta.getColumns(null, "dbo", "employee", null);
You can fetch column name by calling 'getMetaData' method of ResultSet.
ResultSetMetaData metaData= resultSet.getMetaData();
String columnName = metaData.getColumnName(1);
All other column meta data can also be fetching using object of ResultSetMetaData