How to get data in MySQL table into Java JTable? - java

I'm working on Java project, and I need to load a particular set of data in to JTable. Can someone explain to me how to do this? These are my fields in the "mrnform" table in database called "order_processing".
`Date` varchar(10) NOT NULL,
`RegNo` int(11) NOT NULL,
`Description` varchar(50) NOT NULL,
`ItemNo` int(11) NOT NULL,
`Unit` varchar(10) NOT NULL,
`Quantity` int(11) NOT NULL,
`Delivery_Date` varchar(10) NOT NULL,
`Delivery_Address` varchar(10) NOT NULL,
`Site_Name` varchar(30) NOT NULL,

1) construct JDBC Connection for MySql, examples here
2) load data to the JTable by using TableModel, examples here
3) if you'll reall question, post this question here in sscce from

Pseudo code
Design the TableModel (or Vector)
Establish the db connection and retrieve result.
Store database result into TableModel object.
Construct the JTable(tableModel).

Read the manual for the JTable:
http://download.oracle.com/javase/tutorial/uiswing/components/table.html

visit
http://netshor.blog.com/2013/12/31/how-to-get-data-from-mysql-to-jtable/
'//initialize row of jTable int row=0; //start try-catch try{
//create connection with database //execute query //no start loop
while(rs.next()){jTable1.setValueAt(rs.getString(1), row, 0);
jTable1.setValueAt(rs.getString(2), row, 1);
jTable1.setValueAt(rs.getString(3), row, 2);
jTable1.setValueAt(rs.getString(4), row, 3);
jTable1.setValueAt(rs.getString(5), row, 4);
jTable1.setValueAt(rs.getString(6), row, 5);
jTable1.setValueAt(rs.getString(7), row, 6);
//increament in row of jtable. row++; } } catch(Exception e) {
}'

Related

JDBC, Prepared Statement getInt() returns 0

In my DB every question has a valid questionID (primary Key) and categoryID (foreign Key to category table).
The problem is: in the Result Set for every question both IDs are 0 instead of what's written in the DB. All other arguments are filled out correctly.
private ArrayList<Question> questions = new ArrayList<Question>();
private Connection connie;
private PreparedStatement psShowQuestions;
psShowQuestions= connie.prepareStatement("SELECT * FROM question");
ResultSet rs = psShowQuestions.executeQuery();
while (rs.next()) {
questions.add(new Question(rs.getInt("questionID"), rs.getInt("categoryID"), rs.getString("question"), rs.getString("rightAns"), rs.getString("wrong1"), rs.getString("wrong2"), rs.getString("wrong3"), rs.getString("hint")));
}
Collections.shuffle(questions);
Edit 1
Here is the original code (in the post I changed the variables from German to English):
The creation of my SQL table:
CREATE TABLE `frage` (
`frageID` int(11) NOT NULL,
`kategorieID` int(11) DEFAULT NULL,
`frage` varchar(200) NOT NULL,
`richtig` varchar(200) NOT NULL,
`falsch1` varchar(200) NOT NULL,
`falsch2` varchar(200) NOT NULL,
`falsch3` varchar(200) NOT NULL,
`hinweis` varchar(200) NOT NULL,
`anzFalsch` int(11) DEFAULT NULL,
`anzRichtig` int(11) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
private ArrayList<Frage> fragen = new ArrayList<Frage>();
private Connection connie;
private PreparedStatement psGetFragen;
ResultSet rs = psGetFragen.executeQuery();
while (rs.next()) {
fragen.add(new Frage(rs.getInt("frageID"), rs.getInt("kategorieID"), rs.getString("frage"), rs.getString("richtig"), rs.getString("falsch1"), rs.getString("falsch2"), rs.getString("falsch3"), rs.getString("hinweis")));
}
Collections.shuffle(fragen);
Most likely, there is a problem with the constructor. You might have not set questionID and categoryID in the constructor and therefore you are getting the default value of int as 0.

MySQL Error when using Statement.RETURN_GENERATED_KEYS

I inherited an old Servlet/JSP website, which has been updated to Java 1.8.0_201 and MySQL 5.7.28. Recently, I started to get this error when adding new records to the database:
Generated keys not requested. You need to specify Statement.RETURN_GENERATED_KEYS to Statement.executeUpdate(), Statement.executeLargeUpdate() or Connection.prepareStatement().
I googled what was going on, and found that I need to add Statement.RETURN_GENERATED_KEYS to my Statement.executeUpdateQuery, so I did. However, I still get the error. The updated code, and the error occurs at the statement result = stmt.getGeneratedKeys();:
stmt = con.createStatement();
switch(queryType) {
case INSERT_QUERY:
stmt.executeUpdate(query, Statement.RETURN_GENERATED_KEYS);
int autoIncKey = -1;
result = stmt.getGeneratedKeys();
if (result.next()) {
autoIncKey = result.getInt(1);
}
rows = stmt.getUpdateCount();
svr.setGeneratedKey(autoIncKey);
obj.setGeneratedKey(autoIncKey);
svr.setRows(rows); //Insert/Update/Delete
if (rows > 0)
svr.setSuccess(true);
else
svr.setSuccess(false);
break;
However, the insert works and the data is put into the database.
I then thought I should update the Mysql Connector library, so I updated from version 5.4 to mysql-connector-java-8.0.18.jar. Still getting the same error.
I am not using any prepared statements, just a String for the query text. This is the query string:
INSERT INTO Flights(rocket_name, weight, angle, baseline, egg_id, shockcord_id, notes, date, rocketModelID, mission_specialists, flight_engineers, teacher_id) VALUES ('asdfasdfasd', 98.0, 60.0, 60.0, 2, 2, 'sfdg sfdg sdg sfdg sdfg sfdg sfdg', '2020-01-07', 4,'asdfasdf', 'asdfasdfas', 13);
The table definition for Flights:
| Flights | CREATE TABLE `Flights` (
`flight_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`teacher_id` int(11) NOT NULL DEFAULT '0',
`egg_id` int(10) unsigned NOT NULL DEFAULT '0',
`shockcord_id` int(10) unsigned NOT NULL DEFAULT '0',
`rocket_name` varchar(100) NOT NULL DEFAULT '',
`weight` decimal(10,4) unsigned NOT NULL DEFAULT '0.0000',
`angle` decimal(10,5) NOT NULL DEFAULT '0.00000',
`baseline` decimal(10,5) NOT NULL DEFAULT '0.00000',
`date` date NOT NULL DEFAULT '0000-00-00',
`rocketModelID` int(11) unsigned NOT NULL DEFAULT '0',
`flight_engineers` varchar(100) NOT NULL DEFAULT '',
`mission_specialists` varchar(100) NOT NULL DEFAULT '',
`notes` text,
PRIMARY KEY (`flight_id`),
FULLTEXT KEY `search1` (`mission_specialists`),
FULLTEXT KEY `search2` (`flight_engineers`),
FULLTEXT KEY `search3` (`flight_engineers`,`mission_specialists`)
) ENGINE=MyISAM AUTO_INCREMENT=562 DEFAULT CHARSET=latin1
I am not sure how to proceed. Any suggestions would be greatly appreciated!
Mark
Recommend changing your code as follows:
Name the key column
Get the row count from the executeUpdate call
Don't call getGeneratedKeys() if no rows were inserted
rows = stmt.executeUpdate(query, new String[] { "flight_id" });
int autoIncKey = -1;
if (rows > 0) {
result = stmt.getGeneratedKeys();
if (result.next()) {
autoIncKey = result.getInt(1);
}
}
svr.setGeneratedKey(autoIncKey);
obj.setGeneratedKey(autoIncKey);
svr.setRows(rows); //Insert/Update/Delete
svr.setSuccess(rows > 0);
Though, really, a single INSERT statement using VALUES will always insert exactly one row, so checking row count is entirely unnecessary. If the row wasn't inserted, an exception would have been thrown, so your code could be reduced to:
stmt.executeUpdate(query, new String[] { "flight_id" });
try (ResultSet result = stmt.getGeneratedKeys()) {
result.next();
int autoIncKey = result.getInt(1);
svr.setGeneratedKey(autoIncKey);
obj.setGeneratedKey(autoIncKey);
}
svr.setRows(1);
svr.setSuccess(true);

#0001: java.sql.SQLException: Parameter index out of range (1 > number of parameters, which is 0)

I want to delete a row. My TABLES are 'goal' and 'contribute'.It shows above error.
Please tell immediately what's the problem.
Table structure is ,
//goal TABLE
CREATE TABLE `goal` (`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(555) NOT NULL,
`target_value` double NOT NULL,
`target_date` date NOT NULL,
`created_date` datetime NOT NULL,
`status` int(11) NOT NULL,
PRIMARY KEY (`id`))
ENGINE=InnoDB AUTO_INCREMENT=13 DEFAULT CHARSET=utf8
COLLATE=utf8mb4_0900_ai_ci
//Contribute TABLE
CREATE TABLE `contribute`
(`id` int(11) NOT NULL AUTO_INCREMENT,`goal` int(11) NOT NULL,
`amount` double NOT NULL, `date` date NOT NULL,
PRIMARY KEY (`id`),KEY `idgoal_idx` (`goal`),
CONSTRAINT `fk` FOREIGN KEY (`goal`) REFERENCES `goal` (`id`))
ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=utf8m
COLLATE=utf8mb4_0900_ai_ci
//Code
public static boolean delete(int id) {
try {
Connection con = DB.getConnection();
String sql = "ALTER TABLE 'goal' ADD CONSTRAINT 'fk' FOREIGN
KEY('goal') REFERENCES 'goal' ('id') ON DELETE CASCADE ";
PreparedStatement ps = con.prepareStatement(sql);
ps.setInt(1, id);
ps.executeUpdate();
return true;
} catch (Exception ex) {
ex.printStackTrace();
}
return false;
}
In my oppinion your code is bad. You are executing this
String sql = "ALTER TABLE 'goal' ADD CONSTRAINT 'fk' FOREIGN
KEY('goal') REFERENCES 'goal' ('id') ON DELETE CASCADE ";
every time you invoke this method. You should add constraints when creating the tables.
In order to delete a row from some table i suggest you to create a database procedure or function which does it and invoke it through java.
String sql = "{? = call your_schema.your_package.delete_object(?)}";
try (CallableStatement cs = con.createCallableStatement(sql)) {
cs.setInt(1, id);
cs.executeQuery();
}
This is just an example but i think this is the correct way to do it. In this procedure you accept your ID as parameter and delete the row there.
Here's two problem:
1.your sql doesn't contain any parameter keyword : ?
You use java set parameter ps.setInt(1, id), but your sql doesn't contain keyword ?
Example for parameter using ? :
PreparedStatement p = con.prepareStatement("select * from xxxTable where xxx = ?");
p.setString(1, xxx);
More details you can learn from mysql - java.sql.SQLException Parameter index out of range (1 > number of parameters, which is 0) - Stack Overflow
2.Your SQL maybe wrong
ALTER TABLE 'goal' ADD CONSTRAINT 'fk' FOREIGN
KEY('goal') REFERENCES 'goal' ('id') ON DELETE CASCADE
'goal' table doesn't contain 'goal' column.
it should be changed like:
ALTER TABLE `contribute`
ADD FOREIGN KEY (`goal`) REFERENCES `goal`(`id`) ON DELETE CASCADE ;
SQL Fiddle Demo Link

CachedRowSet update a record in H2

I have a H2 DB with a table
CREATE TABLE income_expense
(
amount VARCHAR(255) NOT NULL,
name VARCHAR(255) NOT NULL,
ondate VARCHAR(255) NOT NULL
);
and some random data like INSERT INTO income_expense VALUES ('10','Something','2015-04-15');
then I connect to this DB with JDBC and try to do an UPDATE through CachedRowSet:
public void doUpdate()
{
try
{
Class.forName("org.h2.Driver");
setConnection(
DriverManager.getConnection("jdbc:h2:~/thisdb", "sa", ""));
CachedRowSet crs2 = new CachedRowSetImpl();
crs2.setType(CachedRowSet.TYPE_SCROLL_INSENSITIVE);
crs2.setConcurrency(CachedRowSet.CONCUR_UPDATABLE);
crs2.setCommand(
"SELECT amount, name, ondate FROM income_expense");
crs2.execute(getConnection());
crs2.absolute(1);
crs2.updateString("amount", "22");
crs2.updateString("name" , "33");
crs2.updateString("ondate", "44");
crs2.updateRow();
crs2.acceptChanges();
}
catch (ClassNotFoundException | SQLException e)
{
System.out.println("Error occured." + e);
}
}
this update fails with a message javax.sql.rowset.spi.SyncProviderException: 1 conflicts while synchronizing.
What am I doing wrong to update a record?
Well... CachedRowSet UPDATE worked only after I added a PRIMARY KEY to the table:
ALTER TABLE income_expenses ADD COLUMN id INT NOT NULL AUTO_INCREMENT;
ALTER TABLE income_expenses ADD CONSTRAINT PRIMARY KEY (id);
and specified numbers of columns which form a key for uniquely identifying a row and included that column in a SELECT:
//First column from a command will be the key
crs2.setKeyColumns(new int[]{1});
crs2.setCommand("SELECT id, amount, name, ondate FROM income_expense");

Selecting value from SQL sever using exists

Hai all I am currently doing a project for a hospital clinical lab. I have come across a problem while fetching data from database. The problem is as follows.
I have 2 category of tests namely Single test and Profile test. The master table of tests contain both the category of tests.
MASTER TABLE of TESTS(LAB_TEST_SERVICES)
CREATE TABLE LAB_TEST_SERVICES (inttestid bigint identity NOT NULL IDENTITY,
testid varchar(15) NOT NULL, testname varchar(255) NOT NULL, cptdesc varchar(300),
splinstr varchar(300), tstabbr varchar(25), reordertime numeric(15),
tstduration numeric(15), autocancel numeric(15), minbiltime numeric(15),
status int NOT NULL, maxbiltime numeric(15), PRIMARY KEY (inttestid));
The type and category of test is stored in following table
LAB_SERVICES_TYPE
CREATE TABLE LAB_SERVICES_TYPE (inttypeid bigint identity NOT NULL IDENTITY,
inttestid bigint NOT NULL, testtype varchar(25), visitype int NOT NULL,
appgendr char(2) NOT NULL, PRIMARY KEY (inttypeid));
If the test comes under single test category, I need to fill the details to the columns of following tables namely LAB_SPECIMEN_MAPPING,LAB_PARAMETER_MAPPING and LAB_TEST_LOCATION.
LAB_SPECIMEN_MAPPING
CREATE TABLE LAB_SPECIMEN_MAPPING (inttestspcid bigint identity NOT NULL IDENTITY,
inttestid bigint NOT NULL, intspcid bigint NOT NULL, intcontid bigint NOT NULL,
volcol numeric(15, 3) NOT NULL, volreq numeric(15, 3) NOT NULL,
status int NOT NULL, PRIMARY KEY (inttestspcid));
LAB_PARAMETER_MAPPING
CREATE TABLE LAB_PARAMETER_MAPPING (intparaid bigint identity NOT NULL IDENTITY,
inttestid bigint NOT NULL, paraname varchar(255) NOT NULL,
parseq numeric(15, 3) NOT NULL, resulttype varchar(30), shortname varchar(30),
mand int NOT NULL, derived int NOT NULL, status int NOT NULL,
PRIMARY KEY (intparaid));
LAB_TEST_LOCATION
CREATE TABLE LAB_TEST_LOCATION (intlocid bigint identity NOT NULL IDENTITY,
intlabid bigint NOT NULL, inttestid bigint NOT NULL, status int NOT NULL,
PRIMARY KEY (intlocid));
And if the test comes under Profile Test category then I need to fill the details to the columns of following table namely LAB_PROFILE_TEST_LIST. Here for each profile test I am mapping a single test to it.
LAB_PROFILE_TEST_LIST
CREATE TABLE LAB_PROFILE_TEST_LIST (intproftestid int identity NOT NULL IDENTITY,
intprotestid int NOT NULL, intsintestid int NOT NULL, PRIMARY KEY (intproftestid));
I had done the following code to find the name of test which is mapped ie for single test if it is mapped then the testid(inttestid from LAB_TEST_SERVICES) will be inserted in LAB_SPECIMEN_MAPPING,LAB_PARAMETER_MAPPING and LAB_TEST_LOCATION or if the test is profile test the testid(inttestid from LAB_TEST_SERVICES) will be inserted in LAB_PROFILE_TEST_LIST.
The tests which is mapped ( both single & profile test).(My contribution to my problem).
SELECT *
FROM LAB_TEST_SERVICES lts
WHERE EXISTS
(SELECT lsm.inttestid
FROM LAB_SPECIMEN_MAPPING lsm
WHERE lsm.status = 1
AND lts.inttestid = lsm.inttestid)
AND EXISTS
(SELECT ltl.inttestid
FROM LAB_TEST_LOCATION ltl
WHERE ltl.status = 1
AND lts.inttestid = ltl.inttestid)
AND EXISTS
(SELECT lptr.intprotestid
FROM LAB_PROFILE_TEST_LIST lptr WHERE lts.inttestid = lptr.intprotestid)
So when I tried to do this no tests appear because I know that there will be no tests having both the characteristics of Single and Profile tests. I had done so many things but cant find a solution. Kindly help me to find out the details tests which is mapped both single and profile.I am using Java, Hibernate and SQL SERVER. Thanks in advance

Categories

Resources