How to retrieve data from MySQL database using jdbc? - java

I am trying to retrieve data from MySQL database using eclipse.I am using the same code of JDBC as for a java application...but it does work.

You can do as follows:
Class.forName("com.mysql.jdbc.Driver"); // Setup the connection with the DB
connect = DriverManager.getConnection("jdbc:mysql://localhost/database_name", username,password);
// Statements allow to issue SQL queries to the database ; that's why we need to create one.
statement = connect.createStatement();
// Result set get the result of the SQL query
resultSet = statement.executeQuery("select * from TableName;");
while (resultSet.next()) { //retrieve data
String data = resultSet.getString("column_name");
...
}

Please make sure that your database connection is created successfully then apply queries to retrieve data from database. If your connection is not created then you need to check you driver setting or mysql password setting.

Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection("jdbc:mysql://localhost/database_name",username,password");
Connection class having method like 'createstatement()', with help of this we can query from database.
Statement statement = con.createstatement();
resultSet=statement.executeQuery("select * from tablename");
And finally retrive the data from the 'resultSet' object.

Related

How can I connect to a specific database using Java?

I need a java application that can export some data from a Oracle database and write it to a Excel file everyday. I am really new to JAVA so I am making this app step by step.
First to all I'm going to show the database schema (simplified version):
GLOBAL (allocated in bar.domain.es)
-DATABASE1:
TABLE A
TABLE B
TABLE C
-DATABASE2:
TABLE 1
TABLE 2
One part of my code is:
//Loading the driver
Class.forName("oracle.jdbc.OracleDriver");
System.out.println("Driver Loaded");
//Connecting to Oracle Database
java.sql.Connection con = DriverManager.getConnection(DBURL, DBUSER, DBPASS);
System.out.println("Connection Success");
//Creating statement
Statement stat = con.createStatement();
//Creating the query string
String query ="SELECT count(*) FROM TABLE2 WHERE DATE=150603 AND ID=238";
// Creating the statement to execute the Query
ResultSet rs = stat.executeQuery(query);
where DBURL is: "jdbc:oracle:thin:#bar.domain.es:1521:XE"
With this code I get the message Connection Success so my app is connected to the database schema. However, in this schema there are several databases with several tables on each so my problem comes when I try to launch the query. The program doesn't find TABLE2 which is a table of the DATABASE2. I think that I should specify in someway that I want to search this TABLE2 in DATABASE2 but I don't know how.
You can specify in the query what database the table is in
String query ="SELECT count(*) FROM DATABASE2.TABLE2 WHERE DATE=150603 AND ID=238";

How do I insert column in mssql with java

I don't insert column in mssql with java. Which do I use method ,How do I use?
Thanks
I think that you can simply use a SQL DDL statement :
//st is a Java JDBC Statement object ...
st.executeUpdate("ALTER TABLE yourtable ADD yourcolumn int");
Load the driver, establish connection.
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Connection connection = DriverManager.getConnection("jdbc:sqlserver://servername;database=databasename;integratedSecurity=true");
Create a statement and execute it.
Statement statement = connection .createStatement();
statement.executeUpdate("ALTER TABLE TableName ADD ColumnName DataType");

Getting data from mssql to Eclipse

my first time in eclipse and im trying to get some test data from my sql server,now the problem is i have setup a sql connection using ms jdbc drivers and it seems like it works but when i run my query from eclipse,i get
com.microsoft.sqlserver.jdbc.SQLServerException: Invalid column name
'KategoriName'.
error.My query works fine in sql manager.What could be the problem?I'm adding the code below as well:
String connectionString = "jdbc:sqlserver://192.168.0.155;user=user;password=password";
Connection conn= DriverManager.getConnection(connectionString);
Statement stmt = conn.createStatement();
ResultSet rs;
String sqlconn="select [KategoriName] from [FINSAT6G9].[TBL_Test] whereID=493";
rs = stmt.executeQuery(sqlconn);
String aa = rs.getString("KategoriName");
System.out.println(aa);
Cheers.
Try including the database name in the connection string as so:
String connectionString = "jdbc:sqlserver://192.168.0.155;user=user;password=password;databaseName=FINSAT6G9";
Because, obviously, the error is telling you that the KategoriName column doesn't exist which can only mean 2 things: You have a typo or you are attempting to get the data from the wrong place, either the wrong database or the wrong table.

Creating a "Java DB" database and associated tables in main checking to see if they exist?

I'm creating an applicaation on Netbeans 7! I'd like my application to have a little code in main so that it can create a Java DB connection checking to see if the database and the associate tables exist, if not create the database and the tables in it. If you could provide a sample code, it'd be just as great! I have already looked at http://java.sun.com/developer/technicalArticles/J2SE/Desktop/javadb/ but I'm still not sure how to check for an existing database before creating it!
I'd like my application to have a little code in main so that it can create a Java DB connection checking to see if the database and the associate tables exist, if not create the database and the tables in it.
You can add the create=true property, in the JDBC URL. This creates a Derby database instance if the database specified by the databaseName does not exist at the time of connection. A warning is issued if the database already exists, but as far as I know, no SQLException will be thrown.
As far as creation of the tables is concerned, this is best done on application startup before you access the database for typical transactional activity. You will need to query the SYSTABLES system table in Derby/JavaDB to ascertain whether your tables exist.
Connection conn;
try
{
String[] tableNames = {"tableA", "tableB"};
String[] createTableStmts = ... // read the CREATE TABLE SQL statements from a file into this String array. First statement is for the tableA, and so on.
conn = DriverManager.getConnection("jdbc:derby:sampleDB;create=true");
for(int ctr =0 ; ctr < tableNames.length; ctr++)
{
PreparedStatement pStmt = conn.prepareStatement("SELECT t.tablename FROM sys.systables t WHERE t.tablename = ?");
pStmt.setString(1, tableNames[ctr]);
ResultSet rs = pStmt.executeQuery();
if(!rs.next())
{
// Create the table
Statement stmt = conn.createStatement();
stmt.executeUpdate(createTableStmts[ctr]);
stmt.close();
}
rs.close();
pStmt.close();
}
}
catch (SQLException e)
{
throw new RuntimeException("Problem starting the app...", e);
}
Any non-existent tables may then be created. This is of course, not a good practice, if your application has multiple versions, and the schema varies from one version of the application to another. If you must handle such a scenario, you should store the version of the application in a distinct table (that will usually not change across versions), and then apply database delta scripts specific to the newer version, to migrate your database from the older version. Using database change management tools like DbDeploy or LiquiBase is recommended. Under the hood, the tools perform the same operation by storing the version number of the application in a table, and execute delta scripts having versions greater than the one in the database.
On a final note, there is no significant difference between JavaDB and Apache Derby.
I don't know how much Oracle changed Derby before rebranding it, but if they didn't change too much then you might be helped by Delete all tables in Derby DB. The answers to that question list several ways to check what tables exist within a database.
You will specify the database when you create your DB connection; otherwise the connection will not be created successfully. (The exact syntax of this is up to how you are connecting to your db, but the logic of it is the same as in shree's answer.)
The create=true property will create a new database if it is not exists. You may use DatabaseMetadata.getTables() method to check the existence of Tables.
Connection cn=DriverManager.getConnection("jdbc:derby://localhost:1527/testdb3;create=true", "testdb3", "testdb3");
ResultSet mrs=cn.getMetaData().getTables(null, null, null, new String[]{"TABLE"});
while(mrs.next())
{
if(!"EMP".equals(mrs.getString("TABLE_NAME")))
{
Statement st=cn.createStatement();
st.executeUpdate("create table emp (eno int primary key, ename varchar(30))");
st.close();;
}
}
mrs.close();
cn.close();
Connection conn = getMySqlConnection();
System.out.println("Got Connection.");
Statement st = conn.createStatement();
String tableName = ur table name ;
String query = ur query;
Statement stmt = null;
ResultSet rs = null;
try {
stmt = conn.createStatement();
rs = stmt.executeQuery(query);
System.out.println("Exist");;
}
catch (Exception e ) {
// table does not exist or some other problem
//e.printStackTrace();
System.out.println("Not Exist");
}
st.close();
conn.close();

Mysql read data immediately after writing?

I am using a MySQL DB and a Java JDBC client to access it.
I have a Table that contains session information. Each session is associated with a SessionToken. This token is a Base64 encoded String of a Hash of some of the session values. It should be unique. And is defined as varchar(50) in the db.
When I try to lookup a session by its token I query the database using an sql statement like this:
select SessionId, ClientIP, PersonId, LastAccessTime, SessionCreateTime from InkaSession where SessionToken like 'exK/Xw0imW/qOtN39uw5bddeeMg='
I have a UnitTest that tests this functionality, and it consistently fails, because the query does not return any Session, even tough, I have just written the session to the DB.
My Unit test does the following:
Create Connection via DriverManager.getConnection
Add a session via Sql Insert query
close the connection
create Connection via DriverManager.getConnection
look for the session via sql select
unit test fails, because nothing found
When I step through this UnitTest with the debugger and copy past the select sql that is about to be sent to the db into a mysql command line, it works fine, and I get the session row back.
I also tried to retrive an older session from the db by asking for an older SessionToken. This works fine as well. It only fails, if I ask for the SessionToken immediately after I inserted it.
All connections are on AutoCommit. Nevertheless I tried to set the Transaction Level to "Read Uncommited". This did not work either.
Has anyone any further suggestions?
This is typically caused by the connection not being committed between insert and select.
Did you basically do the following?
statement.executeUpdate("INSERT INTO session (...) VALUES (...)");
connection.commit();
resultSet = statement.executeQuery("SELECT ... FROM session WHERE ...");
Edit I tried the following SSCCE on MySQL 5.1.30 with Connector/J 5.1.7:
public static void main(String[] args) throws Exception {
Class.forName("com.mysql.jdbc.Driver");
Connection connection = null;
Statement statement = null;
ResultSet resultSet = null;
try {
connection = DriverManager.getConnection("jdbc:mysql://localhost/javabase", "root", null);
statement = connection.createStatement();
statement.executeUpdate("INSERT INTO foo (foo) VALUES ('foo')");
resultSet = statement.executeQuery("SELECT id FROM foo WHERE foo = 'foo'");
if (resultSet.next()) {
System.out.println(resultSet.getLong("id"));
} else {
System.out.println("Not inserted?");
}
} finally {
SQLUtil.close(connection, statement, resultSet);
}
}
Works flawlessly. Maybe an issue with your JDBC driver. Try upgrading.
Solved: The two token strings where not identical. One of them had a couple of Zero bytes at the end. (Due to the encrypting and decrypting and padding...) The two strings where visually identical, but MySQL and Java both said, they where not. (And they where right as usual)

Categories