Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I want to learn how to execute basic SQL commands from a Java application. I have been searching for hours and all i can see are stuff to connect to a database. Can anyone provide a sample code to save instances of a simple class containing two fields, a Name(String) and Id(Int) in java.
The JDBC API is a Java API that can access any kind of tabular data, especially data stored in a Relational Database.
The following simple code fragment gives a simple example of these three steps:
public void connectToAndQueryDatabase(String username, String password) {
Connection con = DriverManager.getConnection(
"jdbc:myDriver:myDatabase",
username,
password);
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT a, b, c FROM Table1");
while (rs.next()) {
int x = rs.getInt("a");
String s = rs.getString("b");
float f = rs.getFloat("c");
}
}
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
I'm trying to create a simple JDBC method to delete from my DB, and I'm not sure if I'm going about this the correct way. This is inside one of my services.
Method:
public void deleteLocation(Integer id) {
String DELETE = "DELETE FROM locale WHERE id=?";
namedParameterJdbcTemplate.update(DELETE, new BeanPropertySqlParameterSource(id));
}
I would try changing your update line to
namedParameterJdbcTemplate.update(DELETE, id);.
If you are using spring-boot. Then you should be using spring-data-jpa to manage your database. Jdbc is Hard way of doing this.
If you are using jdbc delete to a specific row use prepared statement. You can refer this:
preparedStatement = connection.prepareStatement("DELETE * from table_name WHERE id= ?");
preparedStatement.setInt(1, id);
return !preparedStatement.execute();
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I have a problem with searching a particular contact using part of a name. I know how it would look like in SQL but I cant implement it using Java.
if (rs.getString(nameTable LIKE '%name1%';)
Consider adding the LIKE clause to your SQL query instead of handling it in java code:
try(PreparedStatment ps = con.prepareStatement("SELECT * " +
" FROM Contact WHERE contactName like ?")) {
ps.setString(1, "%name1%");
try(ResultSet rs = ps.executeQuery()) {
while(rs.next()) {
//process your data
}
}
} catch(Exception e) {
//deal with it
}
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.
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/
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 8 years ago.
Improve this question
I need your help in creating a java bean to retrieve the first 4 columns in a table called "m_connection". I want to retrieve the first 4 columns and store them in variables.
They are all string.
this code sample may help you:
String sql="select one,two,three,four from table where id=1";
Connection con = DriverManager.getConnection("");//get connection here
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(sql);
String[] result = new String[4];
while(rs.next()){
result[0] = rs.getString(1);
result[1] = rs.getString(2);
result[2] = rs.getString(3);
result[3] = rs.getString(4);
}
First of all you need to establish jdbc connection then think for the data retrival
for jdbc connection you need to follow
Load the JDBC driver.
Define the connection URL.
Establish the connection.
Create a statement object.
Execute a query or update.
Process the results.
Close the connection.
refer details