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 ;
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();
}
}
My database is MySQL run from xampp
I have 3 colums id,nazwa,kwota
I keep getting an error:
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown
column 'main' in 'field list'
I think problem is with the
String sql = ("SELECT id, nazwa, kwota");
ResultSet rs = stmt.executeQuery(sql);
but I was looking for almost 2 hours and does not seem to find the answer...
Im desperate, thank you
import java.sql.*;
import javax.sql.*;
public class JdbcDriver{
public static void main(String args[]) {
Connection conn = null;
Statement stmt = null;
String username = "wojtek";
String password = "3445222";
String url = "jdbc:mysql://localhost:3306/javatest";
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(url, username, password);
System.out.println("Connected database successfully...");
//STEP 4: Execute a query
System.out.println("Creating statement...");
stmt = conn.createStatement();
String sql = ("SELECT id, nazwa, kwota");
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 nazwa = rs.getString("nazwa");
int kwota = rs.getInt("kwota");
//Display values
System.out.print("ID: " + id);
System.out.print(", Nazwa: " + nazwa);
System.out.print(", kwota: " + kwota);
}
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
That's a weird wrong SQL statement as pointed below. It's missing FROM table_name
String sql = ("SELECT id, nazwa, kwota");
It should be
String sql = ("SELECT id, nazwa, kwota FROM your_table_name");
^... missing this part
Table is missing in the statement. Better way is always test the query in the database editor before using it.
We always pass SQL Statement in a String in java. If the Statement is Wrong the java compiler gives us an Exception. Same is the case with you, you have passed statement through string. But you have not specified the table from which you are retriving you data.
Your String is:
String sql = ("SELECT id, nazwa, kwota");
You should write the String as:
String sql = ("SELECT id, nazwa, kwota FROM table");
Here table is your table Name from which you are retriving your data.
I wanted to know how to view tables from both schemas (in this example lets say world and world2), through JSF. I can log into my application using a specified schema and view the tables from that schema but I do not know how to log in and view a different schema. (ex. log in as world, view world2 schema table names.)
So I want to ask if there is a way to rewrite tablelist, or maybe repurpose the code to handle sql queries even though the connection is for a specific schema.
Currently I am using:
public TableList[] getTableList() {
try {
String[] TABLE_TYPES = { "TABLE", "VIEW" };
DatabaseMetaData databaseMetaData;
String query = "";
// st = conn.createStatement();
st = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_UPDATABLE);
databaseMetaData = conn.getMetaData();
rs = databaseMetaData.getTables(null, dbaseBean.getUserName(),
null, TABLE_TYPES);
rs.last();
int count = rs.getRow();
tableList = new TableList[count];
rs.beforeFirst();
int i = 0;
while (rs.next()) {
tableList[i] = new TableList(rs.getString("TABLE_NAME"));
i++;
}
} catch (Exception e) {
e.printStackTrace();
FacesMessage msg = new FacesMessage("" + " Error Occured");
FacesContext.getCurrentInstance().addMessage(null, msg);
}
setTableList(tableList);
return tableList;
}
With the following connection:
public boolean connect() {
FacesContext context = FacesContext.getCurrentInstance();
Map<String, Object> m = context.getExternalContext().getSessionMap();
messageBean = (MessageBean) m.get("messageBean");
dbmsUserBean = (DbmsUserBean) m.get("dbmsUserBean");
userName = dbmsUserBean.getUserName();
password = dbmsUserBean.getPassword();
switch (dbmsUserBean.getDbms().toLowerCase()) {
case "mysql":
jdbcDriver = "com.mysql.jdbc.Driver";
url = "jdbc:mysql://" + dbmsUserBean.getDbmsHost() + ":3306/"
+ dbmsUserBean.getDatabaseSchema();
break;
case "db2":
jdbcDriver = "com.ibm.db2.jcc.DB2Driver";
url = "jdbc:db2://" + dbmsUserBean.getDbmsHost() + ":50000/"
+ dbmsUserBean.getDatabaseSchema();
userName = userName.toUpperCase();
break;
case "oracle":
jdbcDriver = "oracle.jdbc.driver.OracleDriver";
url = "jdbc:oracle:thin:#" + dbmsUserBean.getDbmsHost() + ":1521:"
+ dbmsUserBean.getDatabaseSchema();
userName = userName.toUpperCase();
break;
case "odbc":
default:
//
break;
} // end switch
try {
// register driver
Class.forName(jdbcDriver);
// get connection
connection = DriverManager.getConnection(url, userName, password);
// get SQL statement object instance
statement = connection.createStatement(
ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_UPDATABLE);
// retrieve DB meta data
databaseMetaData = connection.getMetaData();
DbaseBean dbaseBean = new DbaseBean();
dbaseBean.setConnection(connection);
dbaseBean.setDatabaseMetaData(databaseMetaData);
dbaseBean.setJdbcDriver(jdbcDriver);
dbaseBean.setUserName(userName);
dbaseBean.setPassword(password);
dbaseBean.setUrl(url);
dbaseBean.setResultSet(resultSet);
m.put("dbaseBean", dbaseBean);
status = true;
}
catch (ClassNotFoundException e) {
// assumes there is a corresponding printException method
// PrintException("Connect: Class not found Exception - could not loadJDBC driver");
status = false;
}
catch (SQLException e) {
// printException(e,"Connect: SQLException information");
status = false;
} catch (Exception e) {
// printException(e,"Connect: Exception information");
status = false;
}
return status;
}
Thank you.
If you are going against Oracle and you have access to the system tables, you can retrieve tables from it with "select user, table_name from system.all_tables where user in ('myuser1', 'myuser2');"
If you want everything, you can go against all_objects where type in 'TABLE', 'VIEW' (and procedure and trigger and...)
If you are going against different databases, you would then have to determine where and what the data dictionaries for each DB are and write code for each one.
DOH - You stated MySQL in the title:
select table_schema, table_name from INFORMATION_SCHEMA.TABLES where table_schema in ('myfirstone', 'mysecondone');
So for example if I have an array list of strings, how do I put them into a database sequentially.
For example if my array list is: "john", "sally", "rob"
How can I come put that into my database such that row 1 is john, row 2 is sally, row 3 is rob.
I was thinking something along the lines of:
for(int i = 0; i < array.size(); i++){
query = "insert into database values(i);
}
But I am not sure if that is the correct approach because I will also be inserting other values into the database other than the array.
I assume you mean a simple insertion;
First you have the database connection, Like this:
public class DBConnection {
final private String url = "jdbc:mysql://localhost/";
final private String databaseName = "test";
final private String user = "root";
final private String password = "159753";
public Connection Connect() {
Connection c = null;
try {
c = DriverManager.getConnection(url + databaseName, user, password);
} catch (SQLException ex) {
Logger.getLogger(DBConnection.class.getName()).log(Level.SEVERE, null, ex);
}
return c;
}}
Below is a simple example of insertion:
public static void main(String[] args) {
Connection con = new DBConnection().Connect();
String sql = "INSERT INTO nameTable (name) values (?)";
PreparedStatement stmt;
try {
stmt = con.prepareStatement(sql);
List<String> names = new ArrayList();
names.add("John");
names.add("Sally");
names.add("Rob");
for (String name : names) {
stmt.setString(1, name);
stmt.execute();
}
stmt.close();
con.close();
} catch (SQLException ex) {
System.err.println("Error = " + ex);
}
}}
PS: But you can use a Java Persistence API too. The wikibook is a good resource to use as reference
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);