This one is related to THIS question which I asked before, this one kinda solve my problem but another problem came up and I'm asking myself 'why is that?'.
here is the codes (BTW I used r2xml.jar in this project) :
private void search() throws Exception{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String url = "jdbc:odbc:*****";
String user = "*****";
String pass = "*****";
Connection conn = DriverManager.getConnection(url, user, pass);
PreparedStatement ps;
ResultSet rs;
String custname = "SELECT pIDNo AS 'Patient ID',pLName AS 'Last Name', pFName AS 'First Name',pMI AS 'M.I.',pSex AS 'Sex',pStatus AS 'Status', pTelNo AS 'Contact No.', pDocID AS 'Doctor ID', pAddr AS 'St. No.',pStreet AS 'St. Name',pBarangay AS 'Barangay',pCity AS 'City', pProvince AS 'Province', pLNameKIN AS 'Last Name',pFNameKIN AS 'First Name',pMIKIN AS 'M.I.',pRelationKIN AS 'Relation',pTotalDue AS 'Total Due' FROM dbo.Patients where pIDNo LIKE '" + "%'";
ps = conn.prepareStatement(custname);
rs = ps.executeQuery();
tblPatient.setModel(DbUtils.resultSetToTableModel(rs));
}
Now here is my concern on the link that I gave, I can't make the TotalDue column data display on my JTable I dunno if it's because of the DATA TYPE that it has which is MONEY. but after using the codes above I manage to display it, but the problem now is that the other columns is now missing, non of them display on my column except TotalDue. Is there any explanation on that? is there a solution? I used this r2xml.jar before and it works fine but now I don't know what is the problem or am I missing something?
Then better go on the hard way, and this works as a charm.
DefaultTableModel tbl = (DefaultTableModel) tblPatient.getModel();
ResultSetMetaData rm = rs.getMetaData(); // this line is useless if you know the column count. (I was too lazy to count :P )
int size = rm.getColumnCount();
while(rs.next()){
Object[] obj = new Object[size];
for(int i=0;i<size;i++){
obj[i] = rs.getObject(i+1);
}
tbl.addRow(obj);
}
Related
So, I want to loop this ResultSet in order to update the table one by one, but the method while(rsl.next()) can't help me do the looping. It's just work once, and then the others are skipped. Can someone help me fix this problem? Thanks in advance
try {
String url = "jdbc:mysql://localhost/minimarket";
String user = "root";
String pass = "";
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection(url, user, pass);
Statement stmt = conn.createStatement();
ResultSet rsl = stmt.executeQuery("SELECT * FROM keranjang WHERE pemesan='"+login.userid+"'");
while (rsl.next()) {
String nb = rsl.getString("nama_barang");
String dtl = rsl.getString("detail");
String beratt = rsl.getString("berat");
String hrga = rsl.getString("harga");
String jmlh = rsl.getString("jumlah");
stmt.executeUpdate("UPDATE barang SET stok=stok+'"+jmlh+"' WHERE nama_barang='"+nb+"' AND detail='"+dtl+"' AND berat='"+beratt+"'");
stmt.executeUpdate("DELETE FROM keranjang WHERE pemesan ='"+login.userid+"' AND nama_barang='"+nb+"'");
}
conn.close();
} catch (Exception error) {
}
System.exit(0);
Problem:
if (rsl.next())
fix:
while (rsl.next())
Debug the app and check if the your connection to the database is valid.
When you execute an executeUpdate on your statement an int is returned and most importantly your result set object rs1 from your query gets closed and can't be accessed anymore since the Statement class only handles one query/result set. I haven't tested this myself but I am pretty sure this is the reason.
The solution is to have a separate Statement object for the update/delete so that the original ResultSet is not affected. Something like below
Statement stmt = conn.createStatement();
Statement updStmt = conn.createStatement();
ResultSet rsl = stmt.executeQuery("SELECT * FROM keranjang WHERE pemesan='"+login.userid+"'");
while (rsl.next()) {
String nb = rsl.getString("nama_barang");
String dtl = rsl.getString("detail");
String beratt = rsl.getString("berat");
String hrga = rsl.getString("harga");
String jmlh = rsl.getString("jumlah");
updStmt.executeUpdate("UPDATE barang SET stok=stok+'"+jmlh+"' WHERE nama_barang='"+nb+"' AND detail='"+dtl+"' AND berat='"+beratt+"'");
updStmt.executeUpdate("DELETE FROM keranjang WHERE pemesan ='"+login.userid+"' AND nama_barang='"+nb+"'");
}
If I've understood your problem correctly, there are two possible problems here:
the resultset is null - I assume that this cant be the case as if it was you'd get an exception in your while loop and nothing would be output
the second problem is that resultset.getString(i++) will get columns 1,2,3 and so on from each subsequent row
I think that the second point is probably your problem here.
Let us say you only had 1 row returned, as follows
Col 1, Col 2, Col3
A , B, C
Your code as it stands would only get A - it wouldn't get the rest of the columns.
I suggest you change your code as follows:
ResultSet resultset = ...;
ArrayList<String> arrayList = new ArrayList<String>();
while (resultset.next()) {
int i = 1;
while(i <= numberOfColumns) {
arrayList.add(resultset.getString(i++));
}
System.out.println(resultset.getString("Col 1"));
System.out.println(resultset.getString("Col 2"));
System.out.println(resultset.getString("Col 3"));
System.out.println(resultset.getString("Col n"));
}
To get the number of columns:
ResultSetMetaData metadata = resultset.getMetaData();
int numberOfColumns = metadata.getColumnCount();
I have data in a MySQL database and I need to show it in a JTextArea:
ps = connection.prepareStatement("SELECT `Name`, FROM `users" + "SELECT `Post`, FROM `history");
I need to show the result of this Query in the TextArea.
Should be something like this:
try{
final String sql = "SELECT Name FROM users;";
PreparedStatement ps = connection.prepareStatement(sql);
ResultSet rs = ps.executeQuery();
if(rs != null){
while(rs.next()){
String name = rs.getString(1);
//Do something with name
}
rs.close();
}
ps.close();
}catch(Exception e){
e.printStackTrace();
}
EDIT:
You have a malformed SQL-Query, like JAMSHAID IQBAL wrote in the comments.
Here is an edited solution, that includes his improvements:
PreparedStatement psUserNames = connection.prepareStatement("SELECT Name FROM users;");
PreparedStatement psPosts = connection.prepareStatement("SELECT Post FROM history;")
1. Extracting data from PreparedStatement:
First you need to get a ResultSet from your PreparedStatement.
This is where all your requested data will be stored in:
ResultSet rsUserNames = psUserNames.executeQuery();
ResultSet rsPosts = psPosts.executeQuery();
then you need to extract the data as Strings from this ResultSet. For example in a way like this (simplified example):
String username = new String();
String post = new String();
rsUserNames.next();
rsPosts.next();
username = rsUserNames.getString("Name");
post = rsPosts.getString("Post");
(Better iterate over all datasets in the ResultSet using a while loop and Exception handling. Here you can see an example)
2. Writing data to JTextArea
Then, a simple way to display the data strings to the JTextArea, is to use the setText() or append() methods. For example:
JTextArea jtextAreaUserName = new JTextArea();
JTextArea jtextAreaPost = new JTextArea();
jtextAreaUserName.setText(username);
jtextAreaPost.setText(post);
Helpful links:
JDBC PreparedStatement example – Select list of the records
Appending text in Java's JTextArea
I have a problem with reading the content of the rows in the database.
I want to show the information (in the console for the moment) about the employee with given position and name. I have built the path ,started the database in H2 but I am not sure I have used PreparedStatement right .
Table "MyTable" not found
I removed the try/catch to be more readable.
static public void Search (JButton a , JFormattedTextField name, JComboBox<String> b ) {
a.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e ) {
Connection con = null;
con = DriverManager.getConnection("jdbc:h2:tcp://localhost/~/test" + "sa" + "");
Statement stm = null;
String ime = name.getText();// reads the name
String poz = (String) b.getSelectedItem();// reads the position
Class.forName("org.h2.Driver");
String sql1 = String.format("SELECT * FROM RABOTNICI WHERE IME = '%s' OR POZICIA = '%s'", ime, poz);
PreparedStatement prstm = null;
prstm = con.prepareStatement(sql1);
ResultSet rs = null;
rs = prstm.executeQuery(sql1);
}
});
}
jdbc:h2:tcp:...
You are using TCP connection but not starting H2 TCP server like this:
http://www.h2database.com/html/tutorial.html#using_server
Normally H2 database is used as embedded without TCP server like this:
http://www.h2database.com/html/tutorial.html#connecting_using_jdbc
jdbc:h2:/path/to/dbfile
I think you had some sources of information and something went wrong down the way.
The way you created a preparedStatement, even if it's parsed correctly, is prone to SQL Injections.
You should first create the statement and only then inject the values.
String sql1 = "SELECT * FROM RABOTNICI WHERE IME = ? OR POZICIA = ?"
PreparedStatement prstm = con.prepareStatement(sql1);
prstm.setString(1, ime);
prstm.setString(2, poz);
Please consult this doc page for correct usage of PreparedStatements
Also, getConnection's argument looks a bit messed up.
con = DriverManager.getConnection("jdbc:h2:tcp://localhost/~/test" + "sa" + "");
The following line should appear before the connection creation.
Class.forName("org.h2.Driver");
I suggest using this tutorial for instruction regarding connection to H2 DB
And last, I'm not sure how do you get the error about "MyTable" its never mentioned in your code snippet.
My code quotes were not tested but I believe are clear enough to get the idea.
(NEWBIE)
public Response editingData(String vin, String editArea, String edit) {
Response result = new Response();
try{
PreparedStatement stmt = conn.prepareStatement("UPDATE car SET ? = ? WHERE vin = ? ");
stmt.setString(1, editArea);
stmt.setString(2, edit);
stmt.setString(3, vin);
stmt.execute();
result.setMessage("Data updated!!!");
}catch(Exception ex) {
result.setMessage("Error");
}
return result;
}
This code should try to execute a preparedStatement and set a response once thats done, else it should catch any errors and set a response, then it should return the response
private Response editCarDetails(){
String vin = ui.getCarVin();
String editArea = ui.editArea();
String edit = ui.edit();
Response result = carDB.editingData(vin, editArea, edit);
ui.displayResponse(result);
}
This module simply sets the values of for the editingData() module, it runs the editingData() module storing its return response value in A response named result and then displays it. Yet nothing is changed in the database...
"UPDATE table SET column = newValue WHERE id = value" works fine in mysql workbench. I've also tried hard coding my value in a string instead of using a preparedStatement, but I get the same results NOTHING. I've read through different questions on stack and though I learn a few useful things none of it help my current situation.
try this:
PreparedStatement stmt = conn.prepareStatement("UPDATE car SET "+ editArea +" = ? WHERE vin = ? ");
stmt.setString(1, edit);
stmt.setString(2, vin);
You can't bind a table or column. You should bind the value.
I've encountered an error and I'm not able to figure out my mistake. I've done my research and haven't found an appropriate answer for my question.
This is my code:
private void jButton6ActionPerformed(java.awt.event.ActionEvent evt) {
String CN, CNo, MN, NT, SNo, VIP, T, D;
CN = TF1.getText();
CNo = TF2.getText();
MN = TF3.getText();
NT = TF4.getText();
SNo = TF5.getText();
VIP = TF6.getText();
T = TF7.getText();
D = TF8.getText();
try
{
Class.forName("java.sql.DriverManager");
Connection con = (Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/devika", "root", "rockgirl12");
Statement stmt = (Statement) con.createStatement();
String query = "INSERT INTO Maintenance VALUES ('"+CN+"',"+CNo+",'"+MN+"',"+NT+",'"+SNo+"','"+VIP+"','"+T+"','"+D+"');";
stmt.executeUpdate(query);
JOptionPane.showMessageDialog(this, "Record added succesfully!");
}
catch(Exception e)
{
JOptionPane.showMessageDialog(this, e.getMessage());
}
}
What I'm trying to do here is I'm adding data to my SQL database through a form I designed in Java Netbeans. I've attached the form I've created here.
My Form
Help would be greatly appreciated :)
Exactly what the error says. The number of columns and the fields in valules do not match. This sort of insert without specifing the column names isn't the best practice by any stretch. You should do
String query = "INSERT INTO Maintenance(col1, col2, col3, col4,..) VALUES ('"+CN+"',"+CNo+",'"+MN+"',"+NT+",'"+SNo+"','"+VIP+"','"+T+"','"+D+"');";
In fact, you shouldn't be doing this sort of string concatenation either. It's far better to use prepared statements. The current approach does not ensure that the data is properly escaped before being saved.