I have a database with all the values stored in a table. I want to print a name from the table using drawString() method. I hv created a resultset and the arraylist. Is there any way to pass a string from database in drawString method??
Please provide me a code or link to a code as I am new to this..Thankyou.
public class AB1 extends JPanel
{ public static void main(String a[]) throws Exception
{
int ID,TC;
String FROM, TO, ATS, DTS, SOURCE, DSTN, TS, ST;
ResultSet rs;
ArrayList<AB> ab = new ArrayList<AB>();
//DATABASE CONNECTION
String TrainNo = "287972";
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
String url = "jdbc:oracle:thin:#127.0.0.1:1521:xe";
Connection c = DriverManager.getConnection(url, "system", "mypcdatabase");
// STORING TABLE IN RESULTSET
int rows = 0;
PreparedStatement st=c.prepareStatement("select * from MT_TRAIN_CONSIST where TRAIN_NUMBER = ?" );
rs=st.executeQuery();
PreparedStatement st1=c.prepareStatement("select * from MT_RAKE_TRAIN_LINK_MASTER where TRAIN_NUMBER = ?");
rs = st1.executeQuery();
PreparedStatement st2=c.prepareStatement("select * from MT_SLIP_TRAIN_INFO where TRAIN_NUMBER = ?");
rs = st2.executeQuery();
while(rs.next())
{
ID = rs.getInt("ID_TRAIN_DEF");
FROM = rs.getString("COACH_FROM");
TO = rs.getString("COACH_TO");
TC = rs.getInt("NUMBER_OF_COACHES");
ATS = rs.getString("ATTACH_TRANSFER_STATION");
DTS = rs.getString("DETACH_TRANSFER_STATION");
SOURCE = rs.getString("TRAIN_SRC");
DSTN = rs.getString("TRAIN_DSTN");
TS = rs.getString("TRANSFER_STATION");
ST = rs.getString("slip_type");
AB obj = new AB();
obj.id = ID;
obj.tc = TC;
obj.from = FROM;
obj.to = TO;
obj.ats = ATS;
obj.dts = DTS;
obj.src = SOURCE;
obj.dstn = DSTN;
obj.ts = TS;
obj.st = ST;
ab.add(obj);
rows++;
}
}
catch(Exception ex)
{
ex.printStackTrace();
}
getImg(new FileOutputStream("C:\\A&B" + TrainNo + ".jpg"), ab);
}
public static void getImg(OutputStream out, ArrayList<AB> ab) throws IOException
{ int imgWidth = 1024, imgHeight = 768;
BufferedImage image = new BufferedImage(imgWidth,imgHeight, BufferedImage.TYPE_INT_ARGB);
Graphics2D gx = image.createGraphics();
gx.setColor(Color.BLUE);
gx.setColor(Color.BLACK);
gx.drawLine(60,350,970,350);
gx.drawLine(970,350,960,340);
gx.drawLine(970, 350, 960, 360);
gx.drawString("", 30 , 330);
gx.drawString("", 960 , 330);
ImageIO.write(image, "PNG", out);
out.close();
}
}
In your these lines
PreparedStatement st = c.prepareStatement("select * from MT_TRAIN_CONSIST where TRAIN_NUMBER = ?");
rs=st.executeQuery();
You forgot to provide any value for the ?, something like
PreparedStatement st = c.prepareStatement("select * from MT_TRAIN_CONSIST where TRAIN_NUMBER = ?");
st.setString(1, TrainNo);
rs=st.executeQuery();
Please Learn Java Naming Conventions and stick to them.
# gagandeep bali
the line is correct
String TrainNo = "287972";
this value is passed in place of the ?
Related
I am having to connect an access database to a netbeans project and create a program that allows a user to search for a football player's name, and have their results displayed on the screen. My problem is that when I do the setTexts at the end, the labels simply turn blank. I do not receive any error messages.
I don't know whether the problem lies in the linking to the database or in parsing the parameters, or somewhere else?
Connection conn = null;
PreparedStatement pst = null;
ResultSet rst = null;
String temp = new String();
String playerID = null;
String name = null;
String surname = null;
String shirtNo = null;
String height = null;
String prefFoot = null;
String nation = null;
try
{
Class.forName("net.ucanaccess.jdbc.UcanaccessDriver");
conn = DriverManager.getConnection("jdbc:ucanaccess://Database4.accdb");
String sql = "SELECT * FROM Players WHERE Name = (?) and Surname = (?)";
pst = conn.prepareStatement(sql);
pst.setString(1, txtfieldFirst.getText());
pst.setString(2, txtfieldSecond.getText());
rst = pst.executeQuery();
if(rst.next())
{
int count = 0;
while(rst.next())
{
playerID = rst.getString("PlayerID");
name = rst.getString("Name");
surname = rst.getString("Surname");
shirtNo = rst.getString("ShirtNo");
height = rst.getString("Height (Metres)");
prefFoot = rst.getString ("PrefFoot");
nation = rst.getString ("Nation");
}
}
conn.close();
}
catch (Exception e)
{
System.out.println(e);
}
Connection con = null;
PreparedStatement pstt = null;
ResultSet rs = null;
String temp2 = new String();
String league = null;
String DOB = null;
String club = null;
boolean tec = false;
String goals15 = null;
String goals16 = null;
String goals17 = null;
String assists15 = null;
String assists16 = null;
String assists17 = null;
try
{
Class.forName("net.ucanaccess.jdbc.UcanaccessDriver");
con = DriverManager.getConnection("jdbc:ucanaccess://Database4.accdb");
String sqll = "SELECT * FROM Stats WHERE PlayerID = (?)";
pstt = con.prepareStatement(sqll);
pstt.setString(1, playerID);
rs = pstt.executeQuery();
if(rs.next())
{
int count = 0;
while(rs.next())
{
league = rs.getString("League");
DOB = rs.getString("DOB");
club = rs.getString("Club");
goals15 = rs.getString("Goals15/16");
goals16 = rs.getString("Goals16/17");
goals17 = rs.getString("Goals17/18");
assists15 = rs.getString("Assists15/16");
assists16 = rs.getString("Assists16/17");
assists17 = rs.getString("Assists17/18");
}
}
con.close();
}
catch (Exception e)
{
System.out.println(e);
}
babyStats pps = new babyStats(league, DOB, club, goals15, goals16, goals17, assists15, assists16, assists17);
babyPlayers ps = new babyPlayers(name, surname, shirtNo, height, prefFoot, nation);
PlayerScreen p = new PlayerScreen(ps, pps); //connection to other screen
p.setVisible(true);
this.setVisible(false);
public PlayerScreen(babyPlayers obj, babyStats objj) //parsed as paramters
{
initComponents();
lblName.setText(obj.getName());
lblSurname.setText(obj.getName());
lblShirtNo.setText(obj.getShirtNo());
lblDOB.setText(objj.getDOB());
lblHeight.setText(obj.getHeight());
lblPFoot.setText(obj.getPreFoot());
lblClub.setText(objj.getClub());
lblNation.setText(obj.getNation()); //these setTexts just make the labels blank
lblGoals16.setText(objj.getGoals1516());
lblGoals17.setText(objj.getGoals1617());
lblGoals18.setText(objj.getGoals1718());
lblAssists16.setText(objj.getAssists1516());
lblAssists17.setText (objj.getAssists1617());
lblAssists18.setText (objj.getAssists1718());
}
I expect the labels to be set with the details coming from the database, but they turn blank instead. I would really appreciate any help. *Update, while debugging, I used system.out.println to print one of the names, and the result came out as null. *Update, I fixed it, the while loops were not meant to be there.
Form 1 is the textfield located
private void tblOrgMouseClicked(java.awt.event.MouseEvent evt) {
Connection cn = null;
Statement st = null;
ResultSet rss = null;
btnSave.setEnabled(false);
btnUpdate.setEnabled(true);
btnDelete.setEnabled(true);
try {
int row = tblOrg.getSelectedRow();
String cell_click = (tblOrg.getModel().getValueAt(row, 0).toString());
String sql = "SELECT * FROM tbl_organization WHERE org_id = '" + cell_click + "'";
cn = DriverManager.getConnection("jdbc:mysql://localhost:3306/db_organization?zeroDateTimeBehavior=convertToNull", "root", "");
st = cn.prepareStatement(sql);
rss = st.executeQuery(sql);
if (rss.next()) {
String addid = rss.getString("org_id");
txtOrgID.setText(addid);
String addname = rss.getString("org_name");
txtOrgName.setText(addname);
String adddesc = rss.getString("org_description");
txtOrgDesc.setText(adddesc);
String addadviser = rss.getString("org_adviser");
txtAdviserName.setText(addadviser);
}
} catch (Exception e) {
}
}
Form 2 is the Jtable
private void tblAdviserList2MouseClicked(java.awt.event.MouseEvent evt) {
// TODO add your handling code here:
Connection cn = null;
Statement st = null;
ResultSet rss = null;
String ab = " ";
try {
int row = tblAdviserList2.getSelectedRow();
String cell_click = (tblAdviserList2.getModel().getValueAt(row, 0).toString());
String sql = "SELECT * FROM tbl_adviser WHERE adviser_id = '" + cell_click + "'";
cn = DriverManager.getConnection("jdbc:mysql://localhost:3306/db_organization?zeroDateTimeBehavior=convertToNull", "root", "");
st = cn.prepareStatement(sql);
rss = st.executeQuery(sql);
if (rss.next()) {
String addid = rss.getString("firstname").concat(ab).concat(rss.getString("middlename")).concat(ab).concat(rss.getString("lastname"));
new FrmOrganization(addid);
this.setVisible(false);
}
} catch (Exception e) {
}
}
To get the value from a particular cell:
Object cellValue = table.getValueAt(row, col);
Alternatively, you can create a TableModel where each row represents a person object, and add a method on that.
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.
I'am trying to update table from multiple columns names(lo1,lo2,...) that are to be taken dynamically. But the values are not getting updated in database.
column names are co1,co2....
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
Connection conn = null;
PreparedStatement pstmt = null;
try{
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost/netbeans","root","");
Statement st = conn.createStatement();
ResultSet rs = st.executeQuery("SELECT * FROM colo");
rs = st.executeQuery("SELECT COUNT(*) FROM colo");
// get the number of rows from the result set
rs.next();
int rowCount = rs.getInt(1);
//txt_ans.setText(String.valueOf(rowCount));
int num_1 =300;
int num_2 =200;
int num_3 =300;
int num_4 =400;
String value = null;
int value1 ;
for(int i=1;i<=rowCount;i++)
{
String sql =("SELECT * FROM colo WHERE id = '"+i+"'");
pstmt = conn.prepareStatement(sql);
rs = pstmt.executeQuery(sql);
while(rs.next())
value = rs.getString("co1");
//txt_ans.setText(String.valueOf(value));
String x = "co2";
if(value.equals("lo1"))
{
// value1= 1;
// txt_ans.setText(String.valueOf(value1));
String sql1 =("update colo set '"+x+"' = '"+num_1+"' where id = '"+i+"'");
pstmt = conn.prepareStatement(sql1);
int r = pstmt.executeUpdate(sql1);
txt_ans.setText(String.valueOf(r));
}
else if(value.equals("lo2"))
{
// value1= 1;
// txt_ans.setText(String.valueOf(value1));
String sql1 =("update colo set '"+ x +"' = '"+num_2+"' where id = '"+i+"'");
pstmt = conn.prepareStatement(sql1);
int r = pstmt.executeUpdate(sql1);
txt_ans.setText(String.valueOf(r));
}
else
{
value1 = 9009;
txt_ans.setText(String.valueOf(value1));
}
}
The problem is with using single quotes for column name i.e, like 'x', so just remove them as shown below:
String sql1 =("update colo set " + x + " = ? where id = ?");//no single quote for x
pstmt = conn.prepareStatement(sql1);
pstmt.setString(1, num_1);
pstmt.setString(2, i);
int r = pstmt.executeUpdate(sql1);
Also, always use prepareStatement's setString, etc.. methods for setting the values which is recommended.
Apply the same concept for the other query inside the else if(value.equals("lo2")) block as well.
This question already has answers here:
com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure
(51 answers)
Closed 6 years ago.
`
import java.sql.*;
public class Match {
public static void main(String args[]) throws Exception{
DBConnection1 con = new DBConnection1();
DBConnection con1 = new DBConnection();
Connection conn = null,conn1=null;
conn = con.getConnection();
conn1 = con1.getConnection();
Statement st = null;
PreparedStatement pst = null;
ResultSet rs = null,rs1 = null;
st = conn.createStatement();
String query1 = "SELECT Name FROM Employee WHERE Name=?";
pst = conn1.prepareStatement(query1);
st.setFetchSize(Integer.MIN_VALUE);
String query = "SELECT name FROM emp";
rs = st.executeQuery(query);
String name = "";
int count = 0;
while(rs.next()){
title = rs.getString("name");
pst.setString(1, title);
rs1 = pst.executeQuery();
while(rs1.next()){
count++;
if(count % 100 == 0)
System.out.println(count);
}
}
System.out.println(count);
}
}
`
I am selecting value from the very large database based on some value from other database . I am running my select query in a while loop. After running my java code after getting many result , i am getting
com.mysql.jdbc.exceptions.jdbc4.CommunicationsException:Communications link failure exception.
I have no idea why this is happening. If you guys have any idea please help
I already read the old questions based on this exception but none of them helps.
import java.sql.*;
public class Match {
public static void main(String args[]) throws Exception{
DBConnection1 con = new DBConnection1();
DBConnection con1 = new DBConnection();
Connection conn = null,conn1=null;
conn = con.getConnection();
conn1 = con1.getConnection();
Statement st = null;
PreparedStatement pst = null;
ResultSet rs = null,rs1 = null;
st = conn.createStatement();
st.setFetchSize(Integer.MIN_VALUE);
String query = "SELECT name FROM emp";
rs = st.executeQuery(query);
String title = "",query1="";
StringBuffer newQuery = new StringBuffer("SELECT Name FROM Employee WHERE ");
int count = 0;
long nameCount = 0L;
while(rs.next()){
nameCount++;
title = rs.getString("name");
query1 = "Name=? or";
pst = conn1.prepareStatement(query1);
pst.setString(1, title);
newQuery.append(pst.toString().substring(pst.toString().indexOf('N'), pst.toString().length())+" ");
}
if ( nameCount > 0 ){
String Query = newQuery.toString().substring(0,newQuery.toString().length() - 3);
rs1 = conn1.createStatement().executeQuery(Query);
while(rs1.next()){
count++;
if(count % 50 == 0)
System.out.println(count);
}
}
}
}
Using PreparedStatement solves the problem of SQL Injection attack. Now the code is working.
I think this code is optimized, but it may have some syntax error:
import java.sql.*;
public class Match {
public static void main(String args[]) throws Exception{
DBConnection1 con = new DBConnection1();
DBConnection con1 = new DBConnection();
Connection conn = null,conn1=null;
conn = con.getConnection();
conn1 = con1.getConnection();
Statement st = null;
ResultSet rs = null,rs1 = null;
st = conn.createStatement();
//String query1 = "SELECT Name FROM Employee WHERE Name=?";
st.setFetchSize(Integer.MIN_VALUE);
String query = "SELECT name FROM emp";
rs = st.executeQuery(query);
String name = "";
StringBuffer newQuery = new StringBuffer("SELECT Name FROM Employee WHERE");
int count = 0;
long nameCount = 0L;
while(rs.next()){
nameCount++;
title = rs.getString("name");
newQuery.append(" Name='" + title + "' or");
}
if ( nameCount > 0 ){
newQuery = newQuery.subString( newQuery.length() - 3);
rs1 = conn1.createStatement.executeQuery( newQuery );
while(rs1.next()){
count++;
if(count % 100 == 0)
System.out.println(count);
}
}
}
}
Link failure may be because of so many query execution. Hence I have made it to fire only one or two queries, and you will get all your results.