Getting the data from SQL and inserting it inside the Java Textfield - java

I've been trying to get the data from the SQL and insert it inside the JTextfield.
Class.forName("com.mysql.cj.jdbc.Driver");
Connection connection =DriverManager.getConnection("jdbc:mysql://localhost:3306/Management", "root", "admin");
Statement st = connection.createStatement();
String sql ="SELECT * FROM information WHERE id =?";
pst=connection.prepareStatement(sql);
pst.setString(1,txtCustomerId.getText());
rs=pst.executeQuery();
if (rs.next()){
String ID = rs.getString("Firstname");
txtFirstname.setText(ID);
}
This code is in the button action, but when I clicked the button, there is nothing happening.

I redo my JFrame and rewrite this code. There is no problem with this code. I think it just override because I copied the previous JFrame.

Related

how to update a data to the database using JDBC

Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con =
DriverManager.getConnection("jdbc:oracle:thin:#localhost:1521:xe",
"system", "9900479852");
Statement stmt =con.createStatement();
ResultSet rs = stmt.executeQuery("select *from registration where emailid='"+str+"' ");
// here im fetching the emailid from data base
while(rs.next()){
emailId = rs.getString("emailId");
mob = rs.getString("mobilenumber");
System.out.println(emailId);
//here we return update query`enter code here`
if(emailId.equals(str)){
stmt.executeQuery("update registration set password='"+s1+"'
where emailId='"+str+" '"); //query is executing but new vales are not updating to the data base
p.println("updated");
}
con.close();
}
trying to update the data to the database i'm not able update ,sql query is executing but data is not updating to data base.
Based on your code snippet, your code is trying to update database but indirectly fall into unnecessary process. Here is my correction, let say we have table (registration) in database consist of structure --> emailId (varchar 10), password (varchar 8).
Suppose you need to update 'registration', for each row when contain emailID = "gmail001" you'll set password to "myPassword". SQL statement for updating is UPDATE registration SET password = "myPassword" WHERE emailId="gmail001"
Back to your code, instead use 'Statement' class, you're prefer to use 'PreparedStatement' class for preconfigured SQL statement. Here is my corrections :
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con = DriverManager.getConnection("jdbc:oracle:thin:#localhost:1521:xe", "system", "9900479852");
String sql = "UPDATE registration SET password=? WHERE emailID=?";
String newPassword = "myPassword";
String keyEmailId = "gmail001";
try{
PreparedStatement stat = con.prepareStatement(sql);
stat.setString(1, newPassword);
stat.setString(2, keyEmailId);
stat.executeUpdate();
}catch(SQLException ex){
ex.printStackTrace();
}
}
For more information please visit oracle javaSE tutorial for JDBC implementations --> https://docs.oracle.com/javase/tutorial/jdbc/basics/prepared.html

Logs for SQL queries in Java using Eclipse

If I am using the below code query the database, where would I find the log file for the process? I am looking for what is being sent to the database. The query works from SQL Server Management Studio. The database is MS-SQL 2008.
try{
Class.forName("net.sourceforge.jtds.jdbc.Driver");
String userName = "dbuser";
String password = "dbpswd";
String url = "jdbc:jtds:sqlserver://server:1043"+";databaseName=databasename";
Connection con = DriverManager.getConnection(url,userName,password);
Statement stm = con.createStatement();
ResultSet rs = stm.executeQuery
("SELECT users.id,users.role FROM users WHERE users.username = 'xusername' AND users.password = 'xpswd' AND users.active = 1");
}
When the code runs it returns
'No current row in the ResultSet.'
If I use
System.out.println(stm);
it returns
net.sourceforge.jtds.jdbc.JtdsStatement#7fd2c698
You have to use
rs.next()
to retrieve the first entry. A ResultSet cursor is initially positioned before the first row.

How to move data from database in textfield using next button in java

here is the code for next button
private void jButton7ActionPerformed(java.awt.event.ActionEvent evt)
{
Connection con=null;
PreparedStatement ps=null;
ResultSet rs=null;
try{
Class.forName("org.apache.derby.jdbc.ClientDriver");
String srt="jdbc:derby://localhost:1527/silicon";
con=DriverManager.getConnection(srt,"rock","brock");
ps=con.prepareStatement("select * from stu where id="+jTextField1.gettext(),
ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_UPDATABLE);
rs=ps.executeQuery();
if(rs.next()) {
jTextField1.setText(String.valueOf(rs.getInt("id")));
jTextField2.setText(rs.getString("nam"));
jTextField3.setText(rs.getString("qu"));
jTextField4.setText(String.valueOf(rs.getInt("pr")));
jTextField5.setText(String.valueOf(rs.getInt("mob")));
jTextField6.setText(String.valueOf(rs.getInt("ad")));
}
else
{
JOptionPane.showMessageDialog(new studentf(), " no record record to navigate in text field");
}
con.close();
}
catch(Exception e)
{
System.out.println(e.getMessage());</i>
}
}
as you see the code i want such way of coding that whenever i click on next button i just move to next record i try most of options which is available every i searched all the topics here but none of them helps me to find my solution i just want on the click on next button the data on Text field changes to next record mean it shows next record i got a project over this i done add search delete first last only 2 buttons unable to do next and
previous button .please help
It looks like there are a good few issues with this code, but I will talk about the most obvious. Excuse my ignorance if I am understanding it wrong, but if your current code executes each time the button is pressed then you are getting a fresh new ResultSet each time, and so each time you press the button your going to display the first result from the new results set.
You need to call rs=ps.executeQuery(); outside of this method so that your not redefining the rs each time. That way calling if(rs.next()){} will move to the next result rather than navigating to the first result each time.
Make the following instance variables;
Connection con = null;
PreparedStatement ps = null;
ResultSet rs = null;
and add following into a constructor (or the like);
Class.forName("org.apache.derby.jdbc.ClientDriver");
String srt = "jdbc:derby://localhost:1527/silicon";
con = DriverManager.getConnection(srt,"rock","brock");
ps = con.prepareStatement("select * from stu",
ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_UPDATABLE);
rs = ps.executeQuery();
A word of warning, you will have to think of a way to close your connection by calling con.close();. You could call con.close() inside of your #Override protected void finalize(){} but there is no 100% guarantee that method will run when your objected is cleared up by the GC.
I hope this helps.
Edit: It seems as though you have a lot of questions about JDBC and PreparedStatements. Here are links to the Oracle JDBC and PreparedStatement tutorials if you need some further reading. A more comprehensive understanding of the subject might be in order.

Operation not allowed after ResultSet Closed error Netbeans MySQL Connectivity

I am creating a program to rename databases in mysql.
I have succeeded in everything and it successfully happens. But in the end of my script, its shows an error/exception saying "Operation not allowed after ResultSet closed". I really have no idea why this error appears even after researching about this error.
Although the full operation is successfully completed and the database is renamed.
Here is my code->
String x = (String) jComboBox1.getSelectedItem(); //jComboBox1 contains the name of current database selected
String z = JOptionPane.showInputDialog("Please enter new name for Database"); //Where user enters the name for new database.
new CustComm().setVisible(false); //Frame that carries the names of tables.
try{
Class.forName("java.sql.DriverManager");
Connection con = (Connection)
DriverManager.getConnection("jdbc:mysql://localhost:"+GlobalParams.portvar+"/",""+k,""+j);
Statement stmnt = (Statement) con.createStatement();
String query = "use "+x;
stmnt.executeQuery(query);
String query2 = "show tables";
ResultSet rs = stmnt.executeQuery(query2);
while (rs.next()){
String dname = rs.getString("Tables_in_"+x);
if(CustComm.jTextArea1.getText().equals("")){
CustComm.jTextArea1.setText(CustComm.jTextArea1.getText()+dname);
}
else{
CustComm.jTextArea1.setText(CustComm.jTextArea1.getText()+"\n"+dname);
}
String y = CustComm.jTextArea1.getText();
Scanner scanner = new Scanner(y);
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
String query3 = "Create database "+z;
stmnt.executeUpdate(query3);
//alter table my_old_db.mytable rename my_new_db.mytable
String query4 = "RENAME TABLE "+x+"."+line+" TO "+z+"."+line;
stmnt.executeUpdate(query4);
String query5 = "drop database "+x;
stmnt.executeUpdate(query5);
}}}
catch(Exception e){
JOptionPane.showMessageDialog(this,e.getMessage());
}
Please help.
You shouldn't execute new queries on statement Statement stmnt = (Statement) con.createStatement(); while you use ResultSet from it, because this will close your ResultSet.
By default, only one ResultSet object per Statement object can be open
at the same time. Therefore, if the reading of one ResultSet object is
interleaved with the reading of another, each must have been generated
by different Statement objects. All execution methods in the Statement
interface implicitly close a statment's current ResultSet object if an
open one exists.
You should create 2 different statements: first for query2 and second for queries 3-5.
Also it's better to use PreparedStatement. You can read about the difference here.
Do you have to do this work via code? Have you looked into tools like Liquibase?

JAVA: get cell from table of mysql

I get a parameter is called 'id' in my function and want to print the cell of the name of this id row.
for example:
this is my table:
id name email
1 alon alon#gmail.com
I send to my function: func(1), so I want it to print 'alon'.
this is what I tried:
static final String url = "jdbc:mysql://localhost:3306/database_alon";
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection(url, "root", "Admin");
String query_txt = "SELECT * FROM authors WHERE id = " + id;
Statement ps2 = con.createStatement();
ResultSet my_rs = ps2.executeQuery(query_txt);
System.out.println(my_rs.getString("name"));
con.close;
Everything is fine, but just one problem. You need to move your ResultSet cursor to the first row before fetching any values: -
Use: -
ResultSet my_rs = ps2.executeQuery(query_txt);
while (my_rs.next()) {
System.out.println(my_rs.getString("name"));
}
As a side note, consider using PreparedStatement to avoid getting attacked by SQL Injection.
Here's how you use it: -
PreparedStatement ps2 = con.prepareStatement("SELECT * FROM authors WHERE id = ?");
ps2.setInt(1, id);
ResultSet my_rs = ps2.executeQuery();
while (my_rs.next()) {
System.out.println(my_rs.getString("name"));
}
You need to use ResultSet.next() to navigate into the returned data:
if (my_rs.next()) {
System.out.println(my_rs.getString("name"));
}
Call my_rs.next(), which will move the ResultSet cursor onto the first row (which you are extracting data out of).
If this is a real application, use PreparedStatements instead of generic Statements. This is an extremely important matter of security if you plan on using user input in SQL queries.

Categories