I am building an application in which you can save deals to database. I'd like to search deals in my database and populate my jtable with relevant results. I want to query my database on keyrelease event. I know it is not an efficient method but I am curious why I can't get it to work.
Below is a sample code that tries to query a database table with ID and country names. There are only 3 country names that start with "D". Somehow I can get country names printed out but can't get them to populate jtable.
The error -
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException" I can't get ResultSet rs1 into a Object[][] . It works fine if I do System.out.println(rs1.getString("Name")
Below is the code -
private void jTextField1KeyReleased(java.awt.event.KeyEvent evt) {
String columnName[] = new String[] { "Name" };
Object oss[][] = new Object[3][];
ResultSet rs1 = null;
int li = 0;
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
java.sql.Connection con = DriverManager.getConnection(Url, User, Password);
Statement st = con.createStatement();
String query = "SELECT * from unit.cntry WHERE Name LIKE '" + abc.getText() + "%';";
rs1 = st.executeQuery(query);
} catch (Exception e) {}
try {
while (rs1.next()) {
oss[li][0] = rs1.getString("Name");
li++;
}
myTable.setModel(new DefaultTableModel(oss, columnName));
} catch (SQLException ex) {
System.out.println(ex.toString());
} finally {
try {
if (rs1 != null) rs1.close();
} catch (SQLException e) {}
}
}
oss[li] = new Object[1];
oss[li][0] = rs1.getString("Name");
Other data structures might be more appealing.
Related
I have a problem with my data view, when showing my data from database to Jtable.
it showing like this,
The pesanan column is fully horizontal
what I want is the result showing like this So the pesanan column is show vertical with create new line using \n
this is my code to showing and get data to the table from phpmyadmin.
private void load_table() {
DefaultTableModel model = new DefaultTableModel();
model.addColumn("pembeli");
model.addColumn("pegawai");
model.addColumn("pesanan");
model.addColumn("harga");
model.addColumn("pembayaran");
model.addColumn("waktu");
//owing data from mysql to Jtable
try {
String sql = "select * from kopitable";
java.sql.Connection conn = (Connection) config.configDB();
java.sql.Statement stm = conn.createStatement();
java.sql.ResultSet res = stm.executeQuery(sql);
while (res.next()) {
model.addRow(new Object[]{
res.getString(1), res.getString(2), res.getString(3), res.getInt(4), res.getString(5), res.getDate(6)
});
}
tabelnya.setModel(model);
} catch (Exception e) {
}
}
And this is my code when i insert data to phpmyadmin.
pesanandata.setText("\nAmericano : "+americano+"\nCapuccino : "+cappuccino+"\nmocha : "+mocha+"\nTopping : "+topping);
try{
String sql = " INSERT INTO kopitable VALUE ('"+namapembeli+"','"+pegawai+"','"+pesanandata.getText()+"','"+totalharga+"','"+pembayarannya.getText()+"','"+java.time.LocalDate.now()+"')";
java.sql.Connection conn=(Connection) config.configDB();
java.sql.PreparedStatement pst=conn.prepareStatement(sql);
pst.execute();
}catch (Exception e){
JOptionPane.showMessageDialog(this, e.getMessage());
}
I am working on a program which will when finished allow the end user to keep track of there sound packs in a database through SQLite. The newest problem I am running into is that I can not get the Select statement to take a JTextField input. The reason that I want to do this is that I already have the text fields linked through the insert method. I have tried switching the variable types in the readAllData method and I am not entirely sure what other way to fix it.
The fields are as follows
PackId
PackName
VendorName
PackValue
what I want to happen is when I hit the Update button I want the data in the database to print out to the console (for now) and I am also going to be adding a select specified records method as well.
Here is the code I do apologize in advance this is a very long project:
public void readAllData() throws SQLException {
Connection conn = DriverManager.getConnection("jdbc:sqlite:packsver3.db");
PreparedStatement ps = null;
ResultSet rs = null;
try {
String sql = "SELECT * FROM packs";
ps = conn.prepareStatement(sql);
rs = ps.executeQuery();
while(rs.next()) {
String PackId = PackId.getText();
String PackName = PackName.getText();
String VendorName = VendorName.getTextField();
String PackValue = rs.getTextField;
System.out.println("All Packs\n");
System.out.println("PackId: " +PackId);
System.out.println("PackName: " +PackName);
System.out.println("VendorName: " +VendorName);
System.out.println("PackValue: " +PackValue+"\n\n");
}
} catch (SQLException e) {
System.out.println(e.toString());
}finally {
try {
assert rs != null;
rs.close();
ps.close();
conn.close();
} catch (SQLException e) {
System.out.println(e.toString());
}
Console Output
I've connected to a MySQL database, which contains four fields (the first of which being an ID, the latter ones each containing varchar strings).
I am trying to get the last row of the database and retrieve the contents of the fields so that I can set them to variables (an int and three strings) and use them later.
So far, I have the bare minimum to make the connection, where do I go from here? As you can see I have tried to write a SQL statement to get the last row but it's all gone wrong from there and I don't know how to split it into the separate fields.
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection con = DriverManager.getConnection("jdbc:mysql://localhost/t", "", "");
Statement st = con.createStatement();
String sql = ("SELECT * FROM posts ORDER BY id DESC LIMIT 1;");
st.getResultSet().getRow();
con.close();
Here you go :
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection con = DriverManager.getConnection("jdbc:mysql://localhost/t", "", "");
Statement st = con.createStatement();
String sql = ("SELECT * FROM posts ORDER BY id DESC LIMIT 1;");
ResultSet rs = st.executeQuery(sql);
if(rs.next()) {
int id = rs.getInt("first_column_name");
String str1 = rs.getString("second_column_name");
}
con.close();
In rs.getInt or rs.getString you can pass column_id starting from 1, but i prefer to pass column_name as its more informative as you don't have to look at database table for which index is what column.
UPDATE : rs.next
boolean next()
throws SQLException
Moves the cursor froward one row from its current position. A
ResultSet cursor is initially positioned before the first row; the
first call to the method next makes the first row the current row; the
second call makes the second row the current row, and so on.
When a call to the next method returns false, the cursor is positioned
after the last row. Any invocation of a ResultSet method which
requires a current row will result in a SQLException being thrown. If
the result set type is TYPE_FORWARD_ONLY, it is vendor specified
whether their JDBC driver implementation will return false or throw an
SQLException on a subsequent call to next.
If an input stream is open for the current row, a call to the method
next will implicitly close it. A ResultSet object's warning chain is
cleared when a new row is read.
Returns:
true if the new current row is valid; false if there are no more rows Throws:
SQLException - if a database access error occurs or this method is called on a closed result set
reference
Something like this would do:
public static void main(String[] args) {
Connection con = null;
Statement st = null;
ResultSet rs = null;
String url = "jdbc:mysql://localhost/t";
String user = "";
String password = "";
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection(url, user, password);
st = con.createStatement();
rs = st.executeQuery("SELECT * FROM posts ORDER BY id DESC LIMIT 1;");
if (rs.next()) {//get first result
System.out.println(rs.getString(1));//coloumn 1
}
} catch (SQLException ex) {
Logger lgr = Logger.getLogger(Version.class.getName());
lgr.log(Level.SEVERE, ex.getMessage(), ex);
} finally {
try {
if (rs != null) {
rs.close();
}
if (st != null) {
st.close();
}
if (con != null) {
con.close();
}
} catch (SQLException ex) {
Logger lgr = Logger.getLogger(Version.class.getName());
lgr.log(Level.WARNING, ex.getMessage(), ex);
}
}
}
you can iterate over the results with a while like this:
while(rs.next())
{
System.out.println(rs.getString("Colomn_Name"));//or getString(1) for coloumn 1 etc
}
There are many other great tutorial out there like these to list a few:
http://www.vogella.com/articles/MySQLJava/article.html
http://www.java-samples.com/showtutorial.php?tutorialid=9
As for your use of Class.forName("com.mysql.jdbc.Driver").newInstance(); see JDBC connection- Class.forName vs Class.forName().newInstance? which shows how you can just use Class.forName("com.mysql.jdbc.Driver") as its not necessary to initiate it yourself
References:
http://zetcode.com/databases/mysqljavatutorial/
This should work, I think...
ResultSet results = st.executeQuery(sql);
if(results.next()) { //there is a row
int id = results.getInt(1); //ID if its 1st column
String str1 = results.getString(2);
...
}
Easy Java method to get data from MySQL table:
/*
* CREDIT : WWW.CODENIRVANA.IN
*/
String Data(String query){
String get=null;
try{
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection con = (Connection)DriverManager.getConnection
("jdbc:mysql://localhost:3306/mysql","root","password");
Statement stmt = (Statement) con.createStatement();
ResultSet rs=stmt.executeQuery(query);
if (rs.next())
{
get = rs.getString("");
}
}
catch(Exception e){
JOptionPane.showMessageDialog (this, e.getMessage());
}
return get;
}
Here is what I just did right now:
import java.sql.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import com.sun.javafx.runtime.VersionInfo;
public class ConnectToMySql {
public static ConnectBean dataBean = new ConnectBean();
public static void main(String args[]) {
getData();
}
public static void getData () {
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/mynewpage",
"root", "root");
// here mynewpage is database name, root is username and password
Statement stmt = con.createStatement();
System.out.println("stmt " + stmt);
ResultSet rs = stmt.executeQuery("select * from carsData");
System.out.println("rs " + rs);
int count = 1;
while (rs.next()) {
String vehicleType = rs.getString("VHCL_TYPE");
System.out.println(count +": " + vehicleType);
count++;
}
con.close();
} catch (Exception e) {
Logger lgr = Logger.getLogger(VersionInfo.class.getName());
lgr.log(Level.SEVERE, e.getMessage(), e);
System.out.println(e.getMessage());
}
}
}
The Above code will get you the first column of the table you have.
This is the table which you might need to create in your MySQL database
CREATE TABLE
carsData
(
VHCL_TYPE CHARACTER(10) NOT NULL,
);
First, Download MySQL connector jar file, This is the latest jar file as of today [mysql-connector-java-8.0.21].
Add the Jar file to your workspace [build path].
Then Create a new Connection object from the DriverManager class, so you could use this Connection object to execute queries.
Define the database name, userName, and Password for your connection.
Use the resultSet to get the data based one the column name from your database table.
Sample code is here:
public class JdbcMySQLExample{
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/YOUR_DB_NAME?useSSL=false";
String user = "root";
String password = "root";
String query = "SELECT * from YOUR_TABLE_NAME";
try (Connection con = DriverManager.getConnection(url, user, password);
Statement st = con.createStatement();
ResultSet rs = st.executeQuery(query)) {
if (rs.next()) {
System.out.println(rs.getString(1));
}
} catch (SQLException ex) {
System.out.println(ex);
}
}
I open new question about the extract data and insert to database. I change and modified the code become like this but still not working.
Flat file:
DT|00000001|TMDWH|UNIFI|00380520160|MAH SIEW YIN|11 |JALAN PP 2/8|TAMAN PUTRA PRIMA|PUCHONG|SELANGOR|47100|MALAYSIA|801110-14-5498||||||VOBB||A||11|JALAN PP 2/8|||TAMAN PUTRA PRIMA
DT|00000002|TMDWH|UNIFI|00322012091|JUNITA BINTI JAMAL|6 10 KONDOMINIUM FAJARIA|JALAN PANTAI BARU|KUALA LUMPUR|KUALA LUMPUR|WILAYAH PERSEKUTUAN|59200|MALAYSIA|800129-09-5078||||||VOBB||A|||JALAN PANTAI BARU|6|KONDOMINIUM FAJARIA|KUALA LUMPUR
Program:
public void massageData(String tmp) {
String[] fields = tmp.replace("\"", " ")
.replace("\'","\'\'")
.trim()
.split("\\s*\\|\\s*");
Connection conn = null;
ResultSet rs = null;
PreparedStatement stmt = null;
String actualMSISDN = parseMSISDN(fields[5]);
if (actualMSISDN.length() > 8) {
String [] aNo = getAreaCode(actualMSISDN).split("\\|");
field[0] = getiCtr(parseMSISDN(fields[5]));
String stateCode = lookupStateCode(State);
String sQuery = "insert into DATA_999 ( ,RecordType,RecordNumber,SourceSystemApplicationId,TargetApplicationId,TelNo,Name,HouseNo,StreetName,AppartmentSuite,TownCity,State,PostalCode,Country,NewIC,OldIC,PassportNo,BRN,LatitudeDecimal,LongitudeDecimal,ServiceType,IndicatorType,CreateDate,Filler,Cr_Nl,HouseNo_New,LotNo_New,StreetName_New,AptNo_New,BuildingName_New,LowIDRange,HighIDRange,SectionName) values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
try {
conn = ds.getConnection();
stmt = conn.prepareStatement(sQuery);
int col = 0;
for (String field : fields) {
stmt.setString(++col, field); // Note: SQL API is 1-based (not zero-based)
}
int dbStat = stmt.executeUpdate();
conn.close();
} catch (SQLException s){
logger.error(s.getMessage());
}
finally {
try {if (stmt != null) stmt.close();} catch (SQLException e) {}
try {if (conn != null) conn.close();} catch (SQLException e) {}
}
}
}
You're actually trying to insert double the amount of fields in 1 row. Also you seem to have an error in your sql query: the first field is absent and there's only a comma there.
It also seems to me that you're not doing anything yourself: you use the advice people give you, change your code and if it doesn't work you create a new question.
So I have a database with 2 tables - Workflows and WorkflowSteps I want to use the rows stored there to create objects in java BUT the catch is that I want to have my database code separated from my application code. From one point onwards - when Workflow/WorkflowSteps objects are create the rest of the application will not have to worry about DB access. So here is what I have:
public Workflow getPendingWorkflowId() {
int workflowid = -1;
Statement statement = null;
ResultSet rs = null;
try {
statement = con.createStatement();
rs = statement.executeQuery("SELECT id FROM xxx.workflows WHERE status = 'NOT-YET-STARTED' LIMIT 1");
while (rs.next()) {
workflowid = rs.getInt("id");
}
statement.close();
rs.close();
} catch (SQLException ex) {
Logger.getLogger(DBAccessor.class.getName()).log(Level.SEVERE, null, ex);
System.out.println("Error fetching workflows id");
}
return new Workflow(workflowid);
}
Each workflow object has a List to store the steps that pertain to a particular Workflow and then each WorkflowStep has a Map which is used to store data taken from a 3rd table:
public List<WorkflowStep> getUnworkedStepsByWFId(int id) {
//can be changed
ArrayList<WorkflowStep> steps = new ArrayList<WorkflowStep>();
Statement statement = null;
ResultSet rs = null;
try {
statement = con.createStatement();
rs = statement.executeQuery("SELECT * FROM `workflow_steps` WHERE `workflow_id` =" + id + " AND status = 'NOT-YET-STARTED'");
while (rs.next()) {
steps.add(new WorkflowStep(rs.getInt(1), rs.getInt(3), rs.getInt(4)));
}
statement.close();
rs.close();
} catch (SQLException ex) {
Logger.getLogger(DBAccessor.class.getName()).log(Level.SEVERE, null, ex);
System.out.println("Error fetching workflows id");
}
return steps;
}
And here is the query for the 3rd table:
public Map getParametersForStep(int workflowId, int workstepPos) {
Statement statement = null;
ResultSet rs = null;
Map<String, String> hMap = new HashMap<String, String>();
try {
statement = con.createStatement();
//MIGHT BE WRONG
rs = statement.executeQuery("SELECT wf.id AS workflowID, ws_steps.id AS workflowStepsID, name, param_value, pathname FROM workflows AS wf INNER JOIN workflow_steps AS ws_steps ON wf.id = ws_steps.workflow_id INNER JOIN ws_parameters ON ws_parameters.ws_id = ws_steps.id INNER JOIN submodule_params ON submodule_params.id = ws_parameters.sp_id AND wf.id =" + workflowId + " AND ws_steps.workflow_position =" + workstepPos);
String paramName = null;
String paramValue = null;
while (rs.next()) {
paramName = rs.getString("name");
if (rs.getString("param_value") == null) {
paramValue = rs.getString("pathname");
} else {
paramValue = rs.getString("param_value");
}
hMap.put(paramName, paramValue);
}
statement.close();
rs.close();
return hMap;
} catch (SQLException ex) {
Logger.getLogger(DBAccessor.class.getName()).log(Level.SEVERE, null, ex);
System.out.println("Error fetching workflow step parameters names");
}
return Collections.emptyMap();
}
Having this code in mind I end up with the following "procedure" to initialize a Workflow with all its WorkflowSteps and their Parameters:
Workflow wf = db.getPendingWorkflowId();
wf.initSteps(db.getUnworkedStepsByWFId(wf.getId()));
Iterator<WorkflowStep> it = wf.getSteps();
while(it.hasNext()) {
WorkflowStep step = it.next();
step.setParameters(db.getParametersForStep(wf.getId(), step.getPosInWorkflow()));
}
I think I have a good level of decoupling but I wonder if this can be refactored somehow - for example probably move the step.setParameters to a method of the WorkflowStep class but then I would have to pass a reference to the database connection (db) to a WorkflowStep object but in my view this will break the decoupling? So how would you people refactor this code?
It seems that you are rolling your own ORM. My suggestion would be to use one of existing ones like Hibernate.
This is the function of an Object Relational Mapper. It serves to abstract your DB access away from your business model. In fact, used properly, an ORM library allows you to write no database code at all.