I have java code which retrieve some data from MySQL with appropriate code in netbeans.The code is below. I want to do multi query such as for example finding total number of products and so on.could you help me please. thanks in advance
import java.sql.*;
public class JavaMysqlSelectExample
{
public static void main(String[] args)
{
try
{
String myDriver = "com.mysql.jdbc.Driver";
String myUrl = "jdbc:mysql://localhost/sample";
Class.forName(myDriver);
Connection conn = DriverManager.getConnection(myUrl, "root", "mypasscode1");
String query = "SELECT * FROM products";
Statement st = conn.createStatement();
ResultSet rs = st.executeQuery(query);
while (rs.next()==true)
{
int code = rs.getInt("code");
String productname = rs.getString("product_name");
String producttype = rs.getString("product_type");
System.out.format(" %d, %s, %s\n", code, productname, producttype);
}
st.close();
}
catch (Exception e)
{
System.err.println("Error message: ");
System.err.println(e.getMessage());
}
}
}
Create another statement then query again. Don't close the connection to database until you finish your job. Until user disconnects, db connection can be alive.(Best case)
Database connection is consuming job for code if you open connection for each request, it will cause a bad performance.
Select count(1) from products : gives you the total number of products
OR
long counter = 0;
while (rs.next()==true)
{
int code = rs.getInt("code");
counter++;
String productname = rs.getString("product_name");
String producttype = rs.getString("product_type");
System.out.format(" %d, %s, %s\n", code, productname, producttype);
}
System.out.println("Total Product Count : " + counter);
Related
I am trying to check if a specific row exists in a table that includes two given parameters: record_id and modifiedDate. So far my code does not work.
public void doSomething(int RECORD_ID) {
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
Date date = new Date();
String modifiedDate = dateFormat.format(date);
Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/db", "user", "pass");
Statement stmt = connection.createStatement();
String checkIfInDB = "select exists(select * from table where reference = ${RECORD_ID} and creation_date = '${modifiedDate}');"
ResultSet rs = stmt.executeQuery(checkIfInDB);
if(rs.next()) {
println "Query in db"
stmt.close();
connection.close();
return;
}
else {
String command = "INSERT INTO table(reference, creation_date) VALUES (${RECORD_ID}, '${modifiedDate}');"
stmt.executeUpdate(command)
println "Success"
stmt.close();
connection.close();
return;
}
}
If the user inserts a RECORD_ID and date that already exists, the program adds it to the table anyway, when it should print 'Query in db'.
I would appreciate any help to solve this issue.
Rather than listing what was wrong with the provided code I offer an example of a working example that could be used to help you along your journey...
public static void main(String[] args) {
int recordId = 1;
String jdbcSource = "jdbc:mysql://localhost:####/";
String user = "****";
String password = "****";
String checkIfInDB = "select count(*) as cnt from example_schema.example_table where example_table.reference = ? and example_table.creation_date = ?";
try (Connection connection = DriverManager.getConnection(jdbcSource, user, password)) {
PreparedStatement stmt = connection.prepareStatement(checkIfInDB);
stmt.setInt(1, recordId);
stmt.setDate(2, java.sql.Date.valueOf(LocalDate.now()));
ResultSet rs = stmt.executeQuery();
if (rs.next()) {
System.out.println("at least one row matched");
return;
} else {
// to-do implement insert statement
return;
}
} catch (SQLException e) {
e.printStackTrace();
}
}
How do i subract an input from mysql database?
Let's say I'm doing a bill and inventory system. So when the user input a quantity on a jtextfield, it'd minus off from the table.
will attach the GUI.
right now, i have written this method
public boolean updateBill(Bill bi) {
boolean success = false;
dbController db = new dbController();
PreparedStatement ps;
try {
myConn = DriverManager.getConnection("jdbc:mysql://localhost:3306/ooadp?useSSL=false", "root", "pass");
Statement myStatement = myConn.createStatement();
String sql = "UPDATE medicalproduct SET quantity = quantity - ? WHERE productID = ?, productName = ?, dosage = ?, price = ?, status = ?" ;
myStatement.executeUpdate(sql);
myConn.close();
} catch (Exception e) {
e.printStackTrace();
}
return success;
}
but then I do not know what to write on my actionPerform and how to link my jtextfield to the sql query.
This is how my gui looks like
Your sql statement is invalid anyway... But if am right, all you want to do is subtract from a field in the database by the value specified in a jTextField
//For example quantity -= txtfieldValue;
If does what you want. You can query for the value of the field, do the subtraction and then finally update the field. Here is an example for updating only the quantity:
public void updateQuantity(String txtFieldValue,String id) throws ClassNotFoundException, SQLException{
Class.forName("com.mysql.jdbc.Driver");
System.out.println("Driver loaded!!!");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/ooadp?useSSL=false", "root", "pass");
System.out.println("Connection created!!!");
PreparedStatement pState;
String sqlRawP1 ="select quantity from medicalproduct where productID=?";//I guess medicalproduct is your table name
pState = conn.prepareStatement(sqlRawP1);
pState.setString(1, id);
ResultSet rSetQuantity = pState.executeQuery();
int countQuantity = 0;
while(rSetQuantity.next()){
countQuantity = rSetQuantity.getInt(1);//Am assumming that quantity is an integer
}
int value = Interger.parseInt(txtFieldValue);
countQuantity-= value;
String sqlRawP2 = "update medicalproduct set quantity=? where productID=?";
pState = conn.prepareStatement(sqlRawP2);
pState.setInt(1,countQuantity);
pState.setString(2, id);
pState.executeUpdate();
}
Hope it will work well..Forgive me if there are minor errors because I haven't tested it myself.
public class alldata {
public static void main(String arg[])
{
String str;
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection("jdbc:oracle:thin:#localhost:1521:xe","system","root");
PreparedStatement stmt2;
String sql="select * from RECORDDATA where ID= ? and COMPANY_NM= ?";
stmt2=con.prepareStatement(sql);
int i=5;
str="Audi";
try
{
stmt2.setInt(1, i);
System.out.println("after setting id");
stmt2.setString(2,str);
System.out.println("after setting string");
}
catch(Exception iner)
{
System.out.println("int coulnm"+iner);
}
try
{
ResultSet showdata=stmt2.executeQuery();
System.out.println("after rs");
while(showdata.next())
{
System.out.println("in next");
System.out.println("\n"+showdata.getInt(1)+showdata.getString(2)+showdata.getString(3)+showdata.getString(4)+showdata.getString(5)+showdata.getString(6)+showdata.getString(7));
System.out.println("after next");
}
}catch(Exception e)
{
e.printStackTrace();
}
}catch(Exception e2)
{
e2.printStackTrace();
}
}
}
if i uses hardcoded values ID=5 and COMPANY_NM=Audi it retrives 3 records from database... but my program accepts these value dynamically from user...so that is not working.... please help...i m stuck at this stage...
showdata.next() method does not executing.. although there are 3 records are present in database.
If you expect more than one record to be returned, why can I not find a loop in your code to iterate those records?
Also, next() will retrieve the next record. Calling it twice means you're looking at the second retrieved record.
Now for other stuff:
Java naming convention is a class name must start with uppercase letter.
You don't need Class.forName("oracle.jdbc.driver.OracleDriver"). That isn't needed for JDBC drivers compatible with Java 6 or later.
Remove all try-catch statements. You're catching errors, then letting code continue running as if nothing was wrong. Don't do that!
You're not release the resources. Use try-with-resources for better resource management. It's also simpler to use.
class Alldata {
public static void main(String arg[]) throws SQLException {
int id = 5;
String name = "Audi";
try (Connection con = DriverManager.getConnection("jdbc:oracle:thin:#localhost:1521:xe", "system", "root")) {
String sql = "select * from RECORDDATA where ID= ? and COMPANY_NM= ?";
try (PreparedStatement stmt = con.prepareStatement(sql)) {
stmt.setInt(1, id);
stmt.setString(2, name);
try (ResultSet rs = stmt.executeQuery()) {
while (rs.next()) {
System.out.printf("\n%d, %s, %s, %s, %s, %s, %s%n", rs.getInt(1),
rs.getString(2), rs.getString(3), rs.getString(4),
rs.getString(5), rs.getString(6), rs.getString(7));
}
}
}
}
}
}
Note that you're using the system schema. You should not create user tables in the system schema.
User system should only be used for database maintenance, e.g. to create new users. It should never be used by an application.
UPDATE
From comments, it would appear that statement works when hardcoded, but not when using ? markers. Just to be sure I got that right, please try this code:
class Alldata {
public static void main(String arg[]) throws SQLException {
try (Connection con = DriverManager.getConnection("jdbc:oracle:thin:#localhost:1521:xe", "system", "root")) {
String sql1 = "select count(*) from RECORDDATA where ID= ? and COMPANY_NM= ?";
try (PreparedStatement stmt = con.prepareStatement(sql1)) {
stmt.setInt(1, 5);
stmt.setString(2, "Audi");
try (ResultSet rs = stmt.executeQuery()) {
if (rs.next())
System.out.println("Count 1: " + rs.getInt(1));
}
}
String sql2 = "select count(*) from RECORDDATA where ID= 5 and COMPANY_NM= 'Audi'";
try (PreparedStatement stmt = con.prepareStatement(sql2)) {
try (ResultSet rs = stmt.executeQuery()) {
if (rs.next())
System.out.println("Count 2: " + rs.getInt(1));
}
}
}
}
}
It should print the same number for both "Count 1" and "Count 2".
System.out.println(showdata.next()); retrieved your first record.
Every call to .next() pushes the pointer forward. So prevent calling .next() if you are not using the retrieved result direct afterwards.
The aim of the code here is to Read a record by selecting a column.
I have following columns in the SQL DB.
------------------------------
|id | Topic | Comment | Time |
------------------------------
What I want to do is:-
Read the DB
Able to select rows by Topic
Show or Return the values of selected rows by Topic
The Topic could be duplicated, however the duplicated values should not been seen during the process of selection but the values of all column should be retrieved (as well as duplicated ones).
public class ReadRecordTopic{
// JDBC driver name and database URL
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost:3306/STUDENTS?user=root&password=";
// Database credentials
//static final String USER = "username";
//static final String PASS = "password";
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
try{
//STEP 2: Register JDBC driver
Class.forName("com.mysql.jdbc.Driver");
//STEP 3: Open a connection
System.out.println("Connecting to a selected database...");
conn = DriverManager.getConnection(DB_URL);
System.out.println("Connected database successfully...");
//STEP 4: Execute a query
System.out.println("Creating statement..." + "\n");
stmt = conn.createStatement();
String sql = "SELECT id, Topic, Comment, Time FROM Registration";
ResultSet rs = stmt.executeQuery(sql);
//STEP 5: Extract data from result set
while(rs.next()){
//Retrieve by column name
int id = rs.getInt("id");
String Topic = (String) rs.getString("Topic");
String Comment = rs.getString("Comment");
String Time = rs.getString("Time");
String menu [] = Topic.split(",");
Object[] selectionValues = menu;
String initialSelection = "";
Object selection = JOptionPane.showInputDialog(null,
"Please select the Topic.", "Reseach Forum Menu",
JOptionPane.QUESTION_MESSAGE, null, selectionValues,
initialSelection);
String a = "Research Topic: " + Topic + "\n";
String b = "[" + Time + "]" + " Comment:" + Comment + "\n";
if(selection == Topic){JOptionPane.showMessageDialog(null, a + b);
}
}
rs.close();
}catch(SQLException se){
//Handle errors for JDBC
se.printStackTrace();
}catch(Exception e){
//Handle errors for Class.forName
e.printStackTrace();
}finally{
//finally block used to close resources
try{
if(stmt!=null)
conn.close();
}catch(SQLException se){
}// do nothing
try{
if(conn!=null)
conn.close();
}catch(SQLException se){
se.printStackTrace();
}//end finally try
}//end try
System.out.println("Goodbye!");
}//end main
}//end JDBCExample
1- Create Registration.class
public class Registration{
private int id;
private String topic;
...
...
...
//getters and setters
}
2- Change your sql and function name for what do yo want and use it.
//for order topic
String sql = SELECT id, Topic, Comment, Time FROM Registration order by topic.
//function for just spesific topic
public class ArrayList<Registration> getRegisWithTopic(String topicName){
String sql = SELECT id, Topic, Comment, Time FROM Registration order by topic WHERE TOpic = topicName ;
}
3- in while create new Registration.class and add to ArrayList and return this list
ArrayList<Registration> newList = new ArrayList<Registration>();
while(rs.next()){
Registration newReg = new Registration();
//Retrieve by column name
newReg.setId(rs.getInt("id"));
newReg.setTopic(rs.getString("Topic"));
...
...
...
//add this obj to list
newList.add(newReg);
}
return newList ;
My Title might not be clear enough. So let me explain the problem . I have to retrieve the values from the database store it in an array list and display it in a jsp page dynamically. for that am using a query
select customer,
id,
0 message
from TableName
My Table Structure:
customer varchar2(20)
id Number
I don't know how to add the column 0 message into the result set since this column is not present in that table.
For example, if we give
select 0 message
from TableName;
The output of the above query will be
message
0
So now my question is how to add this column(message) into my Resultset and Array list?
When you add it to your SQL-query as in your question it should also appear in the resultset...
Just wondering if you are facing any issue with executing the SQL query with the additional (non-existing in DB) column through JDBC.
for eg: - you can execute the below query directly in the database through JDBC
select customer,
id,
0 "message"
from TableName
Sample Code snippet.
Connection conn = DriverManager.getConnection(".....", "...","..");
ps = conn.prepareStatement("select customer, id, 0 \"message\" from your_table");
ResultSet rs = ps.executeQuery();
while(rs.next()){
System.out.printf("%s %s %s", rs.getString("id"), rs.getString("customer"), rs.getString("message"));
}
Hlo.. below code will help you..
package com.smk.jdbc.ps;
import java.util.ArrayList;
public class PreparedStatement {
public static void main(String[] args) {
try{
Class.forName("oracle.jdbc.OracleDriver");
java.sql.Connection conn = null;
java.sql.PreparedStatement ps = null;
String strQry = "select 1 message from dual where 1 = ?";
conn = java.sql.DriverManager.getConnection("jdbc:oracle:thin:#localhost:wzdev", "user","pwd");
ps = conn.prepareStatement(strQry);
ps.setInt(1, 1);
java.sql.ResultSet rs = ps.executeQuery();
while(rs.next()){
java.util.ArrayList<java.sql.ResultSet> ars = new ArrayList<java.sql.ResultSet>();
ars.add(rs);
System.out.println(ars.get(0).getInt("message"));
}
}catch(ClassNotFoundException e){
e.printStackTrace();
}catch(Exception e){
e.printStackTrace();
}
}
}
This code is working fine for sql server.And doing same for whatever u want.
public class ConnectionPool
{
public static void main(String[] args)
{
try
{
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Connection conn = DriverManager.getConnection("","","");
Statement s = conn.createStatement();
ResultSet rs = s.executeQuery("select sRowId, 0 messa from tblAccount");
while(rs.next())
{
list.add(rs.getInt("messa"));
}
System.out.println(list.size());
}
catch (Exception e)
{
e.printStackTrace();
}
}
}