Reading data in java form MySQL - java

I'm writing java code that connects to a database in MySQL. I have a connection but I can't get the data to display in a label in my JFrame. So I'm connected to the database software in my XAMPP database but I can't get the data to display in the label
ResultSet rs;
ResultSetMetaData rsmd = null;
int colCount = 0;
String[] colNames = null;
try {
rs = engine.executeQuery("select * from music");
rsmd = rs.getMetaData();
colCount = rsmd.getColumnCount();
colNames = new String[colCount];
for (int i = 1; i <= colCount; i++) {
colNames[i - 1] = rsmd.getColumnName(i);
}
String[] currentRow = new String[colCount];// array to hold the
// row data
while (rs.next()) { // move the rs pointer on to the next record
// (starts before the 1st)
for (int i = 1; i <= colCount; i++) {
currentRow[i - 1] = rs.getString(i);
}
}
//System.out.println(authenticated);
}
catch (SQLException a)
{
System.err.println("SQLException: " + a.getMessage());
}

use this code its working
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.ResultSetMetaData;
public class Db {
public static void main(String arg[]) throws SQLException,
ClassNotFoundException {
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection(
"jdbc:mysql://localhost/dbname", "root", "");
java.sql.Statement stmt = conn.createStatement();
String query = "select * from music";
ResultSet rs = stmt.executeQuery(query);
ResultSetMetaData rsmd = rs.getMetaData();
int columncount = rsmd.getColumnCount();
for(int i = 1 ; i < columncount ; i ++)
System.out.print(rsmd.getColumnName(i));
System.out.println();
while (rs.next()) {
for(int i = 1 ; i < columncount ; i ++)
{
System.out.print(rs.getString(i));
}
System.out.println();
}
conn.close();
}
}

Since you want to have separate class for DB connection and use this connection somewhere else you could do something like this.
public class SQLConnect {
public static Connection ConnectDb() {
try {
Class.forName("com.mysql.jdbc.Driver");
Connection conn = null;
try {
conn = DriverManager.getConnection("jdbc:mysql://localhost/databasename", "root", "");
} catch (SQLException ex) {
Logger.getLogger(SQLConnect.class.getName()).log(Level.SEVERE, null, ex);
}
return conn;
}
catch (ClassNotFoundException e) {
System.out.println("not connected");
e.printStackTrace();//print extra info if error is thrown
return null;
}
}
}
And use this class as follows
Connection conn = null;
ResultSet rs = null;
PreparedStatement pst = null;
try {
conn = SQLConnect.ConnectDb();
String sql = "SELECT * FROM somedatabase WHERE somevalue = ? ";
pst = conn.prepareStatement(sql);
pst.setString(1, CriminalID);
rs = pst.executeQuery();
if(rs.next()) {
/*
* set values of labels to those from database
*/
jLabel.setText(rs.getString("Column name"));
}
this will get you data from database where some value is equal to whatever you specify

Related

JAVA:How to update/refresh Table after changes made into database

I'm new to java and DBMS. I'm trying to update/refresh the JTable after any changes made into the H2 database when user clicks a same button to show JTable and after writing data into database(when write button is clicked). I tried some methods and read some posts but couldn't find anything essential to my program. The code below illustrates my problem.
This is the method used to read from database and show it on JTable
public void readActiveData() throws IOException, InstantiationException, IllegalAccessException, SQLException {
try {
st = conn.createStatement();
} catch (SQLException sqlex) {
JOptionPane.showMessageDialog(null, "Can't connect to DB. " + sqlex);
dispose();
}
try {
rs = st.executeQuery("SELECT * FROM main_data WHERE expirationDate > NOW() + 1;");
rs.beforeFirst();
while (rs.next()) {
int id = rs.getInt(1);
String ovogNer = rs.getString(2);
String regNum = rs.getString(3);
String itemName = rs.getString(4);
String note = rs.getString(5);
int zHemjee = rs.getInt(6);
int hvv = rs.getInt(7);
int hugatsaa = rs.getInt(8);
today = rs.getDate(9);
int totalPay = rs.getInt(10);
expirationDate = rs.getDate(11);
rows++;
}
regData = new Object[rows][11];
Object[] Colheads = {"Бүртгэлийн дугаар", "Овог нэр", "Регистрийн дугаар", "Барьцаа",
"Тэмдэглэл", "Зээлийн хэмжээ", "Хүү (%)", "Хугацаа", "Огноо", "Нийт төлөх", "Дуусах хугацаа"};
rs = st.executeQuery("SELECT * FROM main_data WHERE expirationDate > NOW() + 1;");
for (int i1 = 0; i1 < rows; i1++) {
rs.next();
for (int j1 = 0; j1 < 11; j1++) {
regData[i1][j1] = rs.getString(j1 + 1);
}
}
model = new DefaultTableModel(regData, Colheads);
table = new JTable(model);
int v = ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED;
int h = ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED;
JScrollPane jsp = new JScrollPane(table, v, h);
activeDataPanel.add(jsp);
rs.close();
st.close();
conn.close();
}
And this is the method i'm using to write data into the database
public void writeDataIntoDB() throws InstantiationException, IllegalAccessException {
ResultSet rs = null;
Connection conn = null;
Statement st = null;
PreparedStatement pst = null;
final String URL = "jdbc:h2:~/registDB";
final String USER = "admin";
final String PASS = "password";
LocalDate currentDate = LocalDate.now();
String input = hugatsaaFld.getText();
long addDays = Long.parseLong(input);
expiration = currentDate.plusDays(addDays);
expirationDate = java.sql.Date.valueOf(expiration);
try {
Class.forName("org.h2.Driver").newInstance();
conn = DriverManager.getConnection(URL, USER, PASS);
String sql = "INSERT INTO main_data(ovogNer,regNum,itemName,note,zHemjee,hvv,hugatsaa,date,totalPay,expirationDate)"
+ "VALUES"
+ "(?,?,?,?,?,?,?,?,?,? )";
pst = conn.prepareStatement(sql);
pst.setString(1, getOvogNer());
pst.setString(2, getRegNum());
pst.setString(3, getItemName());
pst.setString(4, getNote());
pst.setInt(5, +getzHemjee());
pst.setInt(6, +getHvv());
pst.setLong(7, +getHugatsaa());
pst.setDate(8, java.sql.Date.valueOf(LocalDate.now()));
pst.setDouble(9, getTotalPay());
pst.setDate(10, expirationDate);
pst.executeUpdate();
pst.close();
conn.close();
} catch (SQLException se) {
JOptionPane.showMessageDialog(null, "Error: " + se);
} catch (ClassNotFoundException ex) {
ex.printStackTrace();
}
}
This question has been answered here
but it comes down to clearing and rerendering your JTable object. i.e. refresh, the post above explains it quite nicely.
Hope you get it right.

How to retrieve all the name from MySQL?

I want to retrieve all the name and the number of row from MySQL to java. So far I only able to retrieve the total row number but I only get the last name. What's wrong here ?
StaffManagement.java
adminAPI api= new adminAPI();
try {
int num= api.displayCheckBoxAndLabel();
String allName= api.displayName();
System.out.println(num+allName);
}
adminAPI
public int displayCheckBoxAndLabel() throws Exception // get the number of row
{
int count = 0;
String sql="Select count(*) AS adminID from admin";
DatabaseConnection db = new DatabaseConnection();
Connection conn =db.getConnection();
PreparedStatement ps = conn.prepareStatement(sql);
ResultSet rs = ps.executeQuery();
while(rs.next())
{
count= rs.getInt("adminID");
}
ps.close();
rs.close();
conn.close();
return count ;
}
public String displayName() throws Exception // get all the name
{
String name = null;
String sql="Select name from admin";
DatabaseConnection db = new DatabaseConnection();
Connection conn =db.getConnection();
PreparedStatement ps = conn.prepareStatement(sql);
ResultSet rs = ps.executeQuery();
while(rs.next())
{
name= rs.getString("name");
}
ps.close();
rs.close();
conn.close();
return name ;
}
You currently return a single String, and your method iterates all of the admin names (but terminates after the final row, so that's your result). Instead, build a List of names and return that. You could also use a try-with-resources close to close your Connection, Statement and ResultSet instances. Something like
public List<String> displayName() throws Exception // get all the name
{
String sql = "Select name from admin";
List<String> names = new ArrayList<>();
DatabaseConnection db = new DatabaseConnection();
try (Connection conn = db.getConnection();
PreparedStatement ps = conn.prepareStatement(sql);
ResultSet rs = ps.executeQuery()) {
while (rs.next()) {
names.add(rs.getString("name"));
}
}
return names;
}
This might be helpful
private String names[];
int i = 0;
while (rs.next()) {
names[i] = rs.getString("name");
i++;
}
Then you can use a for loop to return each name in StaffManagement.java

Exporting database to csv file with java

so i found this code on the internet, basically what supposedly it can do is backup all the tables from a db, my question is on this line:
res = st.executeQuery("select * from xcms." + tableName);
i get the following excpetion exception: SQLException information
what does xcms. stands for? what else can i put here?
res = st.executeQuery("select * from " + tableName);
btw if i erase xcms. and put it like this ^, i can save only the first table not all the tables, thx
the sourcecode webpage:
https://gauravmutreja.wordpress.com/2011/10/13/exporting-your-database-to-csv-file-in-java/#comment-210
public static void main(String[] args) {
Connection con = null;
String url = "jdbc:mysql://localhost:3306/";
String db = "gg";
String driver = "com.mysql.jdbc.Driver";
String user = "root";
String pass = "";
FileWriter fw;
try {
Class.forName(driver);
con = DriverManager.getConnection(url + db, user, pass);
Statement st = con.createStatement();
ResultSet res = st.executeQuery("SELECT table_name FROM INFORMATION_SCHEMA.TABLES WHERE table_schema = 'gg'");
List<String> tableNameList = new ArrayList<String>();
while (res.next()) {
tableNameList.add(res.getString(1));
}
String filename = "C:\\Users\\Angel Silva\\Documents";
for (String tableName : tableNameList) {
int k = 0;
int j = 1;
System.out.println(tableName);
List<String> columnsNameList = new ArrayList<String>();
res = st.executeQuery("select * from " + tableName);
int columnCount = getColumnCount(res);
try {
fw = new FileWriter("C:\\Users\\Angel Silva\\Documents\\popo1121.csv");
for (int i = 1; i <= columnCount; i++) {
fw.append(res.getMetaData().getColumnName(i));
fw.append(",");
}
fw.append(System.getProperty("line.separator"));
while (res.next()) {
for (int i = 1; i <= columnCount; i++) {
if (res.getObject(i) != null) {
String data = res.getObject(i).toString();
fw.append(data);
fw.append(",");
} else {
String data = "null";
fw.append(data);
fw.append(",");
}
}
fw.append(System.getProperty("line.separator"));
}
fw.flush();
fw.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
con.close();
} catch (ClassNotFoundException cnfe) {
System.err.println("Could not load JDBC driver");
cnfe.printStackTrace();
}catch (SQLException sqle) {System.err.println("SQLException information");}
}
public static int getRowCount(ResultSet res) throws SQLException {
res.last();
int numberOfRows = res.getRow();
res.beforeFirst();
return numberOfRows;
}
public static int getColumnCount(ResultSet res) throws SQLException {
return res.getMetaData().getColumnCount();
}
}
This is what I used:
public void sqlToCSV (String query, String filename){
log.info("creating csv file: " + filename);
try {
FileWriter fw = new FileWriter(filename + ".csv");
if(conn.isClosed()) st = conn.createStatement();
ResultSet rs = st.executeQuery(query);
int cols = rs.getMetaData().getColumnCount();
for(int i = 1; i <= cols; i ++){
fw.append(rs.getMetaData().getColumnLabel(i));
if(i < cols) fw.append(',');
else fw.append('\n');
}
while (rs.next()) {
for(int i = 1; i <= cols; i ++){
fw.append(rs.getString(i));
if(i < cols) fw.append(',');
}
fw.append('\n');
}
fw.flush();
fw.close();
log.info("CSV File is created successfully.");
conn.close();
} catch (Exception e) {
log.fatal(e);
}
}
The xms stands for the Database name, in your Connection in the java program you already are establishing the connection to the Database:
(DriverManager.getConnection(url + db, user, pass);
The string db is the name of the DB to connect to.
So no need to have the xms. .just for example use this query:
"SELECT * FROM "+tableName+";"
This is executed in the database you are connected to, for example ggin your code.
For writting the CSV file chillyfacts.com/export-mysql-table-csv-file-using-java/ may help!
SELECT * FROM <MENTION_TABLE_NAME_HERE> INTO OUTFILE <FILE_NAME> FIELDS TERMINATED BY ',';
Example :
SELECT * FROM topic INTO OUTFILE 'D:\5.csv' FIELDS TERMINATED BY ',';
use opencsv dependency to export SQL data to CSV using minimal lines of code.
import com.opencsv.CSVWriter;
import java.io.FileWriter;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class CsvWriter {
public static void main(String[] args) throws Exception {
CSVWriter writer = new CSVWriter(new FileWriter("filename.csv"), '\t');
Boolean includeHeaders = true;
Statement statement = null;
ResultSet myResultSet = null;
Connection connection = null;
try {
connection = //make database connection here
if (connection != null) {
statement = connection.createStatement();
myResultSet = statement.executeQuery("your sql query goes here");
writer.writeAll(myResultSet, includeHeaders);
}
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}

how to get multiple values from one text field with delimiter and save each to database

actually I have 10-30 dummies to get the value from txtCC, but i'd only used 3 dummies for example below..
So how do I get each values and save it directly to my database without using dummy? It's a big deal coz' my code was too large to compile using those dummies..
THANKS for any help..
private void bSaveActionPerformed(java.awt.event.ActionEvent evt)
{
// Save to database
String cc = txtCC.getText();
String delimiter = ",";
String[] temp;
temp = cc.split(delimiter);
for(int i = 0; i < temp.length; i++)
if(i==0) {
txtC1.setText(temp[0]);
txtC2.setText("0");
txtC3.setText("0"); }
else if (i==1) {
txtC1.setText(temp[0]);
txtC2.setText(temp[1]);
txtC3.setText("0"); }
else if (i==2) {
txtC1.setText(temp[0]);
txtC2.setText(temp[1]);
txtC3.setText(temp[2]); }
try {
String cc1 = txtC1.getText(); int CC1 = Integer.parseInt(cc1);
String cc2 = txtC2.getText(); int CC2 = Integer.parseInt(cc2);
String cc3 = txtC3.getText(); int CC3 = Integer.parseInt(cc3);
int opt = JOptionPane.showConfirmDialog(null,"Are you sure you want to save this record? ");
if (opt == 0){
if(!txtC1.getText().equals("0")) {
stmt=con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
String sql = "Select * from tbl_liqinfo";
rs = stmt.executeQuery(sql);
rs.next();
rs.moveToInsertRow();
rs.updateInt("CC", CC1);
rs.insertRow();
rs.close();
}
if(!txtC2.getText().equals("0")) {
stmt=con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
String sql = "Select * from tbl_liqinfo";
rs = stmt.executeQuery(sql);
rs.next();
rs.moveToInsertRow();
rs.updateInt("CC", CC2);
rs.insertRow();
rs.close();
}
if(!txtC3.getText().equals("0")) {
stmt=con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
String sql = "Select * from tbl_liqinfo";
rs = stmt.executeQuery(sql);
rs.next();
rs.moveToInsertRow();
rs.updateInt("CC", CC3);
rs.insertRow();
rs.close();
}
}
}
catch (SQLException err){
JOptionPane.showMessageDialog(FrmEmpLiquidation.this, err.getMessage());
}
}
Instead of using dummies, create simple small methods and make use of it. This will reduce you line of code. and also easy to understand.
private void bSaveActionPerformed(java.awt.event.ActionEvent evt){
// Save to database
String cc = txtCC.getText();
String delimiter = ",";
String[] temp;
temp = cc.split(delimiter);
for(int i = 0; i < temp.length; i++)
insertData(temp[i]);
}
public void insertData(final String data){
txtC1.setText(data);
try {
String cc1 = txtC1.getText(); int CC1 = Integer.parseInt(cc1);
int opt = JOptionPane.showConfirmDialog(null,"Are you sure you want to save this record? ");
if (opt == 0){
if(!txtC1.getText().equals("0")) {
stmt=con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
String sql = "Select * from tbl_liqinfo";
rs = stmt.executeQuery(sql);
rs.next();
rs.moveToInsertRow();
rs.updateInt("CC", CC1);
rs.insertRow();
rs.close();
}
}
}
catch (SQLException err){
JOptionPane.showMessageDialog(FrmEmpLiquidation.this, err.getMessage());
}
}

How to Store Array value in table column in mySql using java

hello i am trying to retrieve data in two result set. then i have store in both resultset to String Array, after this process i have to store my String array to another table how to so this kindly tell me..
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = (Connection) DriverManager.
getConnection("jdbc:mysql://localhost:3306/lportal", "root", "ubuntu123");
PreparedStatement stmt = (PreparedStatement) con.
prepareStatement("SELECT * FROM Testi_Testimonial where subject = ?");
stmt.setString(1, search);
stmt.execute();
rs = (ResultSet) stmt.getResultSet();
while (rs.next()) {
anArray[i] = rs.getString("subject");
System.out.println(anArray[i]);
i++;
count++;
}
PreparedStatement stmt1 = (PreparedStatement) con.
prepareStatement("SELECT * FROM Testi_Testimonial where subject != ?");
stmt1.setString(1, search);
stmt1.execute();
rs1 = (ResultSet) stmt1.getResultSet();
while (rs1.next()) {
anArray[i] = rs1.getString("subject");
System.out.println(anArray[i]);
i++;
count++;
}
} catch (Exception e) {
e.printStackTrace();
System.out.println("problem in connection");
}
Please tell me how should I store my array to Temp table? my "Temp" table has column subject I want to store myArray to subject column... kindly tell me how to do this.
try this after getting resultset in rs:
PreparedStatement st = (PreparedStatement) con.prepareStatement("insert into temp values(?)");
i=0;
while(rs.next())
{
st.setString(1,anArray[i]);
st.executeUpdate();
i++;
}
You just iterate the arrayList. You got the subject List as respective.
public class TestArrayList {
public static void main(String[] args) {
/*create two arrayList*/
List<String> tempOneList = new ArrayList<String>();
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/vijay", "root", "root");
Statement st = con.createStatement();
ResultSet res = st.executeQuery("SELECT * FROM subjecttable");
while (res.next()) {
tempOneList.add(res.getString("subject"));
}
ResultSet resOne = st.executeQuery("SELECT * FROM subjecttabletwo");
while (resOne.next()) {
tempOneList.add(resOne.getString("subject"));
}
System.out.println("temp/List>>--" + tempOneList.size());
for(int i=0;i<tempOneList.size();i++){
System.out.println(tempOneList.get(i));
}
} catch (Exception e) {
e.printStackTrace();
System.out.println("problem in connection");
}
}
}
PreparedStatement ps =
(PreparedStatement) con.prepareStatement("insert into temp values(?)");
j=0;
while(rs.next())
{
ps.setString(1,anArray[j]);
ps.executeUpdate();
j++;
}

Categories