java sql query code example
Example 1: how to write queries in java
import java.sql.*;
public class JavaMysqlSelectExample
{
public static void main(String[] args)
{
try
{
String myDriver = "org.gjt.mm.mysql.Driver";
String myUrl = "jdbc:mysql://localhost/test";
Class.forName(myDriver);
Connection conn = DriverManager.getConnection(myUrl, "root", "");
String query = "SELECT * FROM users";
Statement st = conn.createStatement();
ResultSet rs = st.executeQuery(query);
while (rs.next())
{
int id = rs.getInt("id");
String firstName = rs.getString("first_name");
String lastName = rs.getString("last_name");
Date dateCreated = rs.getDate("date_created");
boolean isAdmin = rs.getBoolean("is_admin");
int numPoints = rs.getInt("num_points");
System.out.format("%s, %s, %s, %s, %s, %s\n", id, firstName, lastName, dateCreated, isAdmin, numPoints);
}
st.close();
}
catch (Exception e)
{
System.err.println("Got an exception! ");
System.err.println(e.getMessage());
}
}
}
Example 2: sql query in java
stmt = con.createStatement();
Example 3: create statement in jdbc
Connection =
Helps our java project connect to database
Statement =
Helps to write and execute SQL query
ResultSet =
A DataStructure where the data from query result stored
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++
After succesfully created the connect
next step is STATEMENT
Statement statement = connection.createStatement();
We use createStatement() method to create
the statement from our connection.
-The result we get from this type of statement
can only move from top to bottom,
not other way around
Statement statement = connection.
createStatement(ResultSet TYPE_SCROLL_INSENSITIVE
,ResultSet CONCUR_READ_ONLY);
-The result we get from this type of
statement can freely move between rows
Once we have statement we can run
the query and get the result to
ResultSet format
import java.sql.ResultSet;
We use the method executeQuery()
to execute our queries
ResultSet result = statement.
executeQuery("Select * from employees");
Example 4: how to write queries in java
2, Fred, Flinstone, 2010-06-23, false, 6000
3, Barney, Rubble, 2010-06-23, false, 5000
Example 5: sql query in java
ResultSet rs = stmt.executeQuery(query);