Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
How can I connect mysql databases in java and use also in android some app?
The best way to connect java with db, how?
In android their is helper class which has parent class Sqlite which has all the data members and functions to access the through this class.Through this class you can read,write and open data.To know more about this read this link
http://www.codeproject.com/Articles/119293/Using-SQLite-Database-with-Android
To connect to a database you need a Connection object. The Connection object uses a DriverManager. The DriverManager passes in your database username, your password, and the location of the database.
Add these three import statements to the top of your code:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
To set up a connection to a database, the code is this:
Connection con = DriverManager.getConnection( host, username, password );
See this example
try (
// Step 1: Allocate a database "Connection" object
Connection conn = DriverManager.getConnection(
"jdbc:mysql://localhost:8888/ebookshop", "myuser", "xxxx"); // MySQL
// Connection conn = DriverManager.getConnection(
// "jdbc:odbc:ebookshopODBC"); // Access
// Step 2: Allocate a "Statement" object in the Connection
Statement stmt = conn.createStatement();
) {
// Step 3: Execute a SQL SELECT query, the query result
// is returned in a "ResultSet" object.
String strSelect = "select title, price, qty from books";
System.out.println("The SQL query is: " + strSelect); // Echo For debugging
System.out.println();
ResultSet rset = stmt.executeQuery(strSelect);
// Step 4: Process the ResultSet by scrolling the cursor forward via next().
// For each row, retrieve the contents of the cells with getXxx(columnName).
System.out.println("The records selected are:");
int rowCount = 0;
while(rset.next()) { // Move the cursor to the next row
String title = rset.getString("title");
double price = rset.getDouble("price");
int qty = rset.getInt("qty");
System.out.println(title + ", " + price + ", " + qty);
++rowCount;
}
System.out.println("Total number of records = " + rowCount);
} catch(SQLException ex) {
ex.printStackTrace();
}
// Step 5: Close the resources - Done automatically by try-with-resources
}
The most spread method to connect to a remote MySQL database from an Android device, is to put some kind of service into the middle. Since MySQL is usually used together with PHP, the easiest and most obvious way to write a PHP script to manage the database and run this script using HTTP protocol from the Android system.
You can refer: Connect to MySQL using PHP on android as a start.
Additional note: Java traditionally uses JDBC connections to manage data sources. There are many available frameworks that can manage this more efficiently. These frameworks make it easier to write data-access codes and are easier to manage than traditional JDBC code. Such frameworks are available for Android too. Search for them. I'm sure you will find some answers. :)
Use php on server side to connect and maintain MySql Database, then you can use some service to execute that php scripts from Android.If you want to know how to connect PHP MySql And Android here is an example http://www.androidhive.info/2012/05/how-to-connect-android-with-php-mysql/ this uses wamp/lamp server.
if you want to create a database within the app, you can use SqLite Database. Which is very useful when your app requires to maintain an internal Database.Here is an example that illustrate the use of Sqlite http://www.androidhive.info/2013/09/android-sqlite-database-with-multiple-tables/
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I'm trying to create a Java Swing login form. My program has two JTextFields (Username and Password) and a JButton ("Submit"). I've connected this program with an MS Access database.
Here's the code I've written just to connect to the database:
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String url = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=" + "C:\\Libsoft\\Libsoft.accdb";
Connection conn = DriverManager.getConnection(url, "", "");
System.out.println("Connection Succesfull");
I'll use usernamefield.getText() to get the typed username and then I want to
search that in the database. Once the program finds the typed username under the username column, I want to retrieve data from the adjacent cell i.e the cell under the password column. I'll then check whether the typed password matches the one from from the database or not and if it does, I'll grant access to the user.
I'm a beginner and it's my first program that connects to a database. Please help me make it work according to the above mentioned process.
Thanks in advance!
But nowhere did I find a way to retrieve data from the adjacent cell.
I don't know much about SQL but I doubt you would get data from an adjacent cell. You need to know the name of the column in the table.
You need to create a query using SQL. Assuming you have a table (UserTable) with two columns (UserId, Password), you might create a query like (untested code):
try
{
String sql = "Select Password from UserTable where UserId = ?";
PreparedStatement stmt = connection.prepareStatement(sql);
stmt.setString( 1, userName.getText() );
stmt.executeQuery();
if (rs.next()) // userid found, validate the password
{
String password = rs.getString(1);
// test if password matches the value entered in the text field
}
else // user not found
{
System.out.println("Invalid UserId");
}
stmt.close();
}
catch(SQLException e)
{
System.out.println(e);
}
The PreparedStatment is easy to use because it will format the SQL properly for you when using parameters.
For more information about SQL you need to read a text book or you can start with the Java tutorial on JDBC Database Access.
I am looking for a way to save an SQL database and then reference it by means other than localhost which would not work because it is being used on other computers.
I realize that my terminology may not be correct in asking for a means to "package" an SQL database however I am not very sure how to put my desire such a concise title.
I have a database that I created through mySQL here: http://gyazo.com/fcac155a60c0d2587442c3e4807ef98a
I can access this database with no problems through the following code...
try
{
//Get connection
Connection myConn = DriverManager.getConnection("jdbc:mysql://localhost:3306/term_database","root", "_cA\"#8X(XHm+++E");
//**********
//Connection myConn = DriverManager.getConnection("jdbc:mysql:translationDatabase","root", "_cA\"#8X(XHm+++E");
//**********
//create statement
Statement myStmt = myConn.createStatement();
//execute sql query
ResultSet myRs = myStmt.executeQuery("select * from terms WHERE idNumber=" +termNumber);
//process result set
while(myRs.next()){
term= (myRs.getString(language));
}
}
catch (Exception exc)
{
exc.printStackTrace();
}
However, I assume that my users will be on different computers and so a "//localhost" reference will not work. They do not have access to the internet either. So I aim to include the database in my program's files to be downloaded with the software or to include it in the jar. I was not able to find any means to do that online. The code I surrounded with *'s was an attempt to reference translationDatabase.sql which I saved through the program mySQL into my software's directory but it did not work as shown here: http://gyazo.com/e9d4339435dedecab4e7ad960e9b13b6
To recap: I am looking for a way to save an SQL database and then reference it by means other than localhost which would not work because it is being used on other computers.
The idiomatic terminology is "embedded" or "serverless" database.
There are several pure-java solutions. There is also the popular SQLite, which you can manipulate via its command line client, or via a third-party JDBC driver (example 1, example 2)
Any of the above solutions will require that you convert your existing MySQL database to the target system..
Alternatively, you may consider bundling your application with MySQL server (possibly with an automated installation process, so that installation is invisible to the end-user).
Running Netcool 7.3.1. Looking for simple api to access Object Server Tables. I've already done the run an SQL command from nco_sql, and scraped the output into a C# data table, but wondering if there was some type of api that I could use for either C# or Java to access table data?
If you can use a more up-to-date version of Omnibus, you can use the built-in HTTP / REST API.
http://www-01.ibm.com/support/knowledgecenter/SSSHTQ_8.1.0/com.ibm.netcool_OMNIbus.doc_8.1.0/omnibus/wip/api/concept/omn_api_http_overview.html?lang=en
You may need to use sybase database adapter so far I have used below three ways to query netcool object server:
Free TDS - This is free sybase client.
Jconn3 - this is paid sybase client, but if you are using WebGUI/Impact, this driver comes with TIP.
nco_sql - here you may need to create a file with query and then pass it to nco_sql. This require extra effort to parse column wise information as output will be on console.
I prefer jconn3, simple and similar to jdbc driver, you only need this jar in classpath.
You can write your own java program to connect to Objectserver by simply initiating
//Load Sybase Driver
Class.forName("com.sybase.jdbc3.jdbc.SybDriver");
String url = "jdbc:sybase:Tds:" + host + ":" + port;
con = DriverManager.getConnection(url, user, pass);
Execute Statements
Statement stat = conn.createStatement();
ResultSet result = stat.executeQuery("Select count(*) from alerts.status");;`
I have tried to connect the mysql database with the frontend with the help of JDBC driver. But i dont know how acna we implement connectivity to connect the two different databases with each other with the help of JDBC driver.
You can create two connections. One for the first database and the other for the second database. You can send commands to the first database using the first connection and you can send commands to the second database using the second connection. Your application will serve the purpose of connecting the two databases as you can select rows from one database, parse them and insert the resulting records into the other.
There is no magic in JDBC that allows you to 'connect the two database with each other'. You need to code this yourself. You create two connections, one for each database and then you write the queries and transformations to get your data from database 1 to database 2.
try (
Connection connectionToDb1 = DriverManager.getConnection(
"jdbc:firebirdsql://serverA/database1", "username", "password");
Connection connectionToDb2 = DriverManager.getConnection(
"jdbc:firebirdsql://serverB/database2", "username", "password");
Statement selectFrom1 = connectionToDb1.createStatement();
ResultSet rsFrom1 = selectFrom1.executeQuery(
"SELECT columnA, columnB FROM tableX");
PreparedStatement insertTo2 = connectionToDb2.prepareStatement(
"INSERT INTO tableY(column1, column2) VALUES (?, ?)");
) {
while (rsFrom1.next()) {
insertTo2.setString(1, rsFrom1.getString("columnA"));
insertTo2.setString(2, rsFrom1.getString("columnB"));
insertTo2.executeUpdate();
}
}
Note that this isn't a complete example: for production purposes you would disable auto commit, and use batch updates.
There are tools that can do this for you, but tool and library suggestions are off topic on SO, but I'd suggest you search for ETL (or extract, transform, load), or maybe for datapump.
I need use SQL without working with MySQL. Just from Java create account, databases, export and import databases. Its possible? Or I should prefer XML for it?
you can of course do it via a Statement that executes the MySQL commands for creating users:
Connection con = ...; //initialize your mysql connection
Statement s = con.createStatement();
s.execute( "CREATE USER ... " );
See the mysql page here for the syntax of create user statement.