hi im new to coding stuffs and i really want to know how to set jLabel with a data from sql server.
i got some codes but its for table and not Label, also it required us to insert the value first so it can be set. someone please help me.
try{
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
String url = "jdbc:sqlserver://localhost:1433;databaseName=GUGUNet";
Connection con = DriverManager.getConnection(url, "sa","gugu");
String query = "insert into Home.HomeTable (Nama, Durasi, PC)VALUES(?,?,?)";
PreparedStatement ps = con.prepareStatement(query);
ps.setString(1, nama.getText());
ps.setString(2, (String) homecombo.getSelectedItem());
ps.setString(3, pc.getText());
if (nama.getText().trim().matches("[a-z A-Z]+") && pc.getText().trim().matches("[0-9]+") && homecombo.getSelectedItem()!="0")
{
ps.executeUpdate();
Statement st = con.createStatement();
ResultSet rs = st.executeQuery("Select ID, Nama From Home.HomeTable");
etable.setModel(DbUtils.resultSetToTableModel(rs));
reset();
//insert();
JOptionPane.showMessageDialog(null, "Data Berhasil Disimpan");
}
else
{
JOptionPane.showMessageDialog(null, "Silahkan isi data dengan benar");
}
Related
I'm trying to make a register page into my servlet project.
If the username is already taken, I want to show an error message.
Heres my code :
String uname=request.getParameter("uname");
String pass=request.getParameter("pass");
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con= (Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/covid","root","fbfbfb333*");
String query = "SELECT * FROM users WHERE username = ?";
pstmt = (PreparedStatement) con.prepareStatement(query);
pstmt.setString(1, uname);
rs = pstmt.executeQuery();
if(rs.next()) {
PreparedStatement pst = (PreparedStatement) con.prepareStatement(" insert into users(username,password) values(?,?)");
pst.setString(1, uname);
pst.setString(2, pass);
pst.executeUpdate();
response.sendRedirect("login.jsp");
} else {
System.out.println("Username " + uname + " already exists.");
}
} catch (Exception e) {
e.printStackTrace();
}
But when I add a new users , it says " username already taken " whether it exist or not.
What should I do?
Switch the condition, if there is a result set data means that the username is taken, else insert new username
if(rs.next()) {
System.out.println("Username " + uname + " already exists.");
} else {
PreparedStatement pst = (PreparedStatement) con.prepareStatement(" insert into users(username,password) values(?,?)");
pst.setString(1, uname);
pst.setString(2, pass);
pst.executeUpdate();
response.sendRedirect("login.jsp");
}
i am creating a simple employee payroll system leave part. I am ran into the problem with when i add the leave information for employee. all leave information will add all the employees who works on the company. when the new employee comes if i add the leave information for the new employee the leave information again add into the existing employee also.i need to add only new employee only leave information how to do the task.existing record not added again.
employee table
leave table
this is code which i tried for but no error but not working.
String cas = txtcas.getValue().toString();
String anu = txtanu.getValue().toString();
String med = txtmed.getValue().toString();
String year = txtyear.getText();
try {
int c;
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost/spay","root","");
PreparedStatement pst1 = con.prepareStatement("select empno from registation");
ResultSet rs = pst1.executeQuery();
String empNoValue1 = rs.getString("empno");
PreparedStatement pst2 = con.prepareStatement("select empno from leaves");
String empNoValue = rs.getString("empno");
ResultSet rs1 = pst2.executeQuery();
while (rs.next()) {
if(rs1.next())
{
if(empNoValue1.equals(empNoValue))
{
}
}
else
{
pst = con.prepareStatement("insert into leaves(empno,casual,annual,medical,year)values(?,?,?,?,?)");
pst.setString(1,empNoValue); // employee no how to give
pst.setString(2, cas);
pst.setString(3, anu);
pst.setString(4, med);
pst.setString(5, year);
pst.executeUpdate();
}
}
JOptionPane.showMessageDialog(null,"Leave Insertedddddd");
If I understood it right you want to increase the ID values of some workers.
Connection con = null;
Statement stmt = null;
int id = 0;
try {
Class.forName("org.postgresql.Driver");
con = DriverManager.getConnection("url", "username", "pwd");
con.setAutoCommit(true);
stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT id FROM userlist ORDER BY id DESC LIMIT 1");
while (rs.next()) {
id = rs.getInt("id");
}
id++;
stmt.execute("INSERT INTO userlist (id) VALUES (" + String.valueOf(id) + ");");
} catch (Exception e) {
e.printStackTrace();
}
I used postgresql so you have to change the queries a bit. The principle is getting the worker with the highest ID, increment the ID by one and rewrite the new ID with maybe other data.
I hope I could help you
String user = request.getParameter("uname");
String pwd = request.getParameter("pass");
String pwd1 = request.getParameter("pass");
String pwd2 = request.getParameter("pass");
try{
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/logindb";
Connection con = DriverManager.getConnection(url, "root", "root");
String sql = "select * from register";
PreparedStatement ps = con.prepareStatement(sql);
ps.setString(1, pwd);
ps.setString(2, request.getParameter("uname"));
ResultSet rs = ps.executeQuery();
if(rs.next())
{
sql = "update register set pass=? where uname=? ";
ps = con.prepareStatement(sql);
ps.setString(1, pwd);
ps.setString(2, request.getParameter("uname"));
ps.executeUpdate();
out.println("password changed");
}
}
catch(Exception e)
{
out.println(e);
}
This Is my code and it will show me an error like this
java.sql.SQLException: Parameter index out of range (1 > number of parameters, which is 0).**
Here:
String sql = "select * from register";
PreparedStatement ps = con.prepareStatement(sql);
ps.setString(1, pwd);
ps.setString(2, request.getParameter("uname"));
You are trying to set parameters that aren't there. Looks like a copy-and-paste error. Those last 2 lines shouldn't be there.
I want to retrieve a users name from the username and password that they have entered into textfields. i want to pass these values as parameter to method which will then identify the users name for printout. please help. something like this...
public void getUser(String username, String password)throws SQLException{
String qry = "SELECT UserName From USER....";
Connection con = null;
PreparedStatement stmt = null;
try{
con = DriverManager.getConnection("URL");
stmt = con.prepareStatement(qry);
stmt.executeUpdate();
If not is an update or an insert, don't use executeUpdate()
You must use executeQuery().
Try this:
Connection con = null;
PreparedStatement stmt = null;
ResultSet rs = null;
String qry = "SELECT UserName From USER where username=? and password=?";
try{
con = DriverManager.getConnection("URL");
stmt = con.prepareStatement(qry);
stmt.setString(1, username);
stmt.setString(2, password);
rs = stmt.executeQuery();
while (rs.next()) {
System.out.println(rs.getString("UserName"));
}
...
Regards
Assuming that you want to get the user's full name from db and your table structure is something like this:
fullname | username | password
you could do the following:
Connection c = null;
PreparedStatement s = null;
try {
c = DriverManager.getConnection("URL");
s = c.prepareStatement("SELECT fullname FROM user WHERE username=? and password=?");
s.setString(1, username);
s.setString(2, password);
ResultSet rs = s.executeQuery();
if(rs.next())
return rs.getString("fullname");
return null; // no user found!
} catch(SQLException e) {
System.err.println(e.getMessage());
} finally {
// close s and c
}
Note: This assumes that the password that is passed to the method is in the same "form" as it is stored in db (i.e. either plain text or hashed (+salted))
try this its very simple example
private boolean validate_login(String id,String password) {
try{
Class.forName("org.sqlite.JDBC"); // MySQL database connection
Connection conn = DriverManager.getConnection("jdbc:sqlite:studentdb.sqlite");
PreparedStatement pst = conn.prepareStatement("Select * from student_table where id=? and password=?");
pst.setString(1, id);
pst.setString(2, password);
ResultSet rs = pst.executeQuery();
if(rs.next())
return true;
else
return false;
try{
Class.forName("org.sqlite.JDBC"); // MySQL database connection
Connection conn = DriverManager.getConnection("jdbc:sqlite:studentdb.sqlite");
PreparedStatement pst = conn.prepareStatement("Select * from student_table where id=? and password=?");
pst.setString(1, id);
pst.setString(2, password);
ResultSet rs = pst.executeQuery();
if(rs.next())
return true;
else
return false;
}
catch(Exception e){
e.printStackTrace();
return false;
}
}
Im trying to use PreparedStatement to my SQLite searches. Statement works fine but Im getting problem with PreparedStatement.
this is my Search method:
public void searchSQL(){
try {
ps = conn.prepareStatement("select * from ?");
ps.setString(1, "clients");
rs = ps.executeQuery();
} catch (SQLException ex) {
ex.printStackTrace();
}
}
but Im getting this error:
java.sql.SQLException: near "?": syntax error at
org.sqlite.DB.throwex(DB.java:288) at
org.sqlite.NestedDB.prepare(NestedDB.java:115) at
org.sqlite.DB.prepare(DB.java:114) at
org.sqlite.PrepStmt.(PrepStmt.java:37) at
org.sqlite.Conn.prepareStatement(Conn.java:231) at
org.sqlite.Conn.prepareStatement(Conn.java:224) at
org.sqlite.Conn.prepareStatement(Conn.java:213)
thx
Columns Parameters can be ? not the table name ;
Your method must look like this :
public void searchSQL()
{
try
{
ps = conn.prepareStatement("select * from clients");
rs = ps.executeQuery();
}
catch (SQLException ex)
{
ex.printStackTrace();
}
}
Here if I do it like this, it's working fine, see this function :
public void displayContentOfTable()
{
java.sql.ResultSet rs = null;
try
{
con = this.getConnection();
java.sql.PreparedStatement pstatement = con.prepareStatement("Select * from LoginInfo");
rs = pstatement.executeQuery();
while (rs.next())
{
String email = rs.getString(1);
String nickName = rs.getString(2);
String password = rs.getString(3);
String loginDate = rs.getString(4);
System.out.println("-----------------------------------");
System.out.println("Email : " + email);
System.out.println("NickName : " + nickName);
System.out.println("Password : " + password);
System.out.println("Login Date : " + loginDate);
System.out.println("-----------------------------------");
}
rs.close(); // Do remember to always close this, once you done
// using it's values.
}
catch(Exception e)
{
e.printStackTrace();
}
}
Make ResultSet a local variable, instead of instance variable (as done on your side). And close it once you are done with it, by writing rs.close() and rs = null.
Passing table names in a prepared statement is not possible.
The method setString is when you want to pass a variable in a where clause, for example:
select * from clients where name = ?
thx for replies guys,,,
now its working fine.
I noticed sql query cant hold ? to columns too.
So, this sql query to PreparedStatement is working:
String sql = "select * from clients where name like ?";
ps = conn.prepareStatement(sql);
ps.setString(1, "a%");
rs = ps.executeQuery();
but, if I try to use column as setString, it doesnt work:
String sql = "select * from clientes where ? like ?";
ps = conn.prepareStatement(sql);
ps.setString(1, "name");
ps.setString(2, "a%"):
rs = ps.executeQuery();
Am I correct? or how can I bypass this?
thx again