SQL query isn't working when embedded in java - sql

I'm trying to connect the SQL plus database with java but it's not working , I'm using netbeabs ide 8.0.2
Here i have pasted following cod
e in my submit button but when I execute it then it goes for the JOptionPane which is in else part whereas it should go for the if part. I'm working on it but I've got no solution can u help please
String sql ="select * from ADMINTABLE where APOST = ? and USERNAME = ? and PASSWORD = ?";
try {
pst = con.prepareStatement(sql)
pst.setString(1, jComboBox1.getSelectedItem().toString());
pst.setString(2,jTextField1.getText());
pst.setString(3, Arrays.toString(jPasswordField1.getPassword()));
rs = pst.executeQuery();
if (rs.next()) {
rs.close();
pst.close();
con.close();
setVisible(false);
Admin ob = new Admin();
ob.setVisible(true);
} else
JOptionPane.showMessageDialog(null,"username and password not matched Please Enter Again !!!");
} catch (SQLException e) {
JOptionPane.showMessageDialog(null,e);
}

Related

JSP database connection and data insert

I am trying to connect to the database and insert only one value in the database using JSP. i have made table category with 2 columns namely Category_id and Category_name, where Category_id is auto increment . so i want to insert only category name into the table. the problem is , i am not able to insert.
the following the code i have written:
String cname = request.getParameter("cname");
try{
// Register JDBC driver
Class.forName("com.mysql.jdbc.Driver");
// Open a connection
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/infoshare", "root", "");
// Execute SQL query
Statement stmt = conn.createStatement();
String sql;
sql = "INSERT INTO catagory(Catagory_name) VALUES("+cname+")";
//ResultSet rs = stmt.executeQuery(sql);
//out.print(cname);
stmt.executeUpdate(sql);
out.print("<h1>Hello</h1>");
// Clean-up environment
//rs.close();
stmt.close();
conn.close();
}catch(SQLException se){
//Handle errors for JDBC
se.printStackTrace();
}catch(Exception e){
//Handle errors for Class.forName
e.printStackTrace();
}
After trying several times, i got the answer as follows:
String cname = request.getParameter("cname");
String cstatus = request.getParameter("cstatus");
try{
// Register JDBC driver
Class.forName("com.mysql.jdbc.Driver");
// Open a connection
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/infoshare", "root", "");
// Execute SQL query
Statement stmt = conn.createStatement();
//
String sql;
sql = "INSERT INTO category(Category_name,status) values('"+cname+"','"+cstatus+"')";
stmt.executeUpdate(sql);
// ResultSet rs = stmt.executeQuery(sql);
response.sendRedirect("add_category.jsp");
// Clean-up environment
//rs.close();
stmt.close();
conn.close();
}catch(SQLException se){
//Handle errors for JDBC
se.printStackTrace();
}catch(Exception e){
//Handle errors for Class.forName
e.printStackTrace();
}
}

Not able to update multiple rows, table being locked

I'm trying to update multiple records with 'CLOSED' status wherever the column has few values.
But, it returns me
Error code :-913, Error message :[SQL0913] Row or object BBT_00008 in BB type *FILE in use.
Here is my code
public void updateIdsStatus(boolean allIdCreated, List<String> ids) throws ClassNotFoundException, SQLException, BBException {
if(ids.size() > 0) {
Connection con = null;
PreparedStatement ps = null;
con = DBUtil.getConnection();
try {
String sql;
if (allIdCreated) {
logger.info("Updating the status of the ids as CLOSED");
sql = "UPDATE <table> SET STATUS = 'CLOSED' WHERE BBDIDNOPK IN ('"+StringUtils.join(ids, "', '") +"') ";
} else {
logger.info("Updating the status of the deals as NEW");
sql = "UPDATE <table> SET STATUS = 'NEW' WHERE BBDIDNOPK IN ('"+StringUtils.join(ids, "', '") +"') ";
}
logger.info("updateIdsStatussql :"+sql);
ps = con.prepareStatement(sql);
ps.executeUpdate();
} catch (SQLException e) {
logger.info(e.getErrorCode()+"-"+e.getMessage());
throw new BBException (e.getErrorCode(), e.getMessage());
} catch (Exception e) {
logger.info(e);
} finally {
try{
if(ps != null)
ps.close();
if (con != null)
con.close();
} catch (SQLException se) {
se.printStackTrace();
}
}
}
}
The query which it prints is
UPDATE <table name> SET STATUS = 'CLOSED' WHERE BBDIDNOPK IN ('abc34569sf', 'abc38511hu')
Why the table is being locked?
P.S : No other person is running the code other than me & no one is accesing the database(DB2).
Where is List<String> ids comming from?
Assuming an SQL statement in another part of the code that accesses the same rows, then it's likely the source of your locks.
Include that code also...
Without it, some suggestions
pass in the connection, so that the locks are within the same connection
close the prior RS/connection first
update the rows within the first statement

Login verification from sqlite not working correctly

Hi everyone I was told by a friend that if I struggle I should go on this website for some guidance. I am a casual after hours programmer and I just do it to enrich my mind. I have a problem at the moment where I want my program to have a login screen and use my sqlite database to verify the username, password and division (administrator, admin, user) before you get to log into the main menu of the program. Now I use Netbeans to do my java programming as it makes it way easier for me and so far it works for the first password and administrator "division" but as soon as I add someone as let say admin or a user nothing happens and I have tried everything I could read up on on the internet as I said I am home schooled when it comes to programming as it is just a hobby and a interest of mine, any advise or a pointer to a website where I can teach myself how to fix my problem will help me.Here is my current code I hope I am posting this correctly:
`private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
String sql ="select Id,Username,Password,Division from Users where (username =? and password= ? and division=?)";
try{
int count = 0;
pst = conn.prepareStatement(sql);
pst.setString(1, txt_username.getText());
pst.setString(2, txt_password.getText());
pst.setString(3, txt_combo.getSelectedItem().toString());
rs = pst.executeQuery();
while (rs.next()){
int Username =rs.getInt(1);
Emp.empnum = Username;
String username = rs.getString("username");
Emp.empname = username;
count = count+1;
}
String access = (txt_combo.getSelectedItem().toString());
if(access =="Administrator,Admin,User"){
if(count == 1){
JOptionPane.showMessageDialog(null, "Success");
MainMenu j = new MainMenu();
j.setVisible(true);
this.dispose();
}else {
JOptionPane.showMessageDialog(null, "The Username or Password you entered was incorrect!");
}
}
}catch (Exception e){
JOptionPane.showMessageDialog(null, e);
}
finally {
try{
rs.close();
pst.close();
}catch (Exception e){
}
}
}`
IU found the function Boolean here is how my code worked perfectly after using it if anyone can see anyway I can better it any advise will do but it works 100%. 'String sql ="select Id,Username,Password,Division from Users where (username =? and password= ? and division=?)";
try{
int count = 0;
boolean foundUser = false;
pst = conn.prepareStatement(sql);
pst.setString(1, txt_username.getText());
pst.setString(2, txt_password.getText());
pst.setString(3, txt_combo.getSelectedItem().toString());
rs = pst.executeQuery();
while (rs.next()){
int Username =rs.getInt(1);
Emp.empnum = Username;
String username = rs.getString("username");
Emp.empname = username;
foundUser = true;
count = count+1;
}
String access = (txt_combo.getSelectedItem().toString());
if (foundUser) {
JOptionPane.showMessageDialog(null, "Success");
MainMenu j = new MainMenu();
j.setVisible(true);
this.dispose();
}else {
JOptionPane.showMessageDialog(null, "The Username or Password you entered was incorrect!");
}
}catch (Exception e){
JOptionPane.showMessageDialog(null, e);
}
finally {
try{
rs.close();
pst.close();
}catch (Exception e){
}
}'

Select and Update accdb database in ASP.net

I am able to select information from my database and retrieve information, but why cant i use the same to update the database?
Commandstring is what i use to write my SQL Sentences.
Not Working:
DatabaseConnection.Commandstring = ("UPDATE tbl_login SET Time='"+Settings.UpdateRecord+"' WHERE Username='"+Settings.LoginName+"' ");
Connection code:
public static string ConString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source='" + System.Web.HttpContext.Current.Server.MapPath("MainData.accdb") + "'; Persist Security Info = False;";
public static string Commandstring;
public static object result;
public static void Connect() {
using (OleDbConnection con = new OleDbConnection(DatabaseConnection.ConString)) {
con.Open();
Debug.WriteLine("Connection to DB Established");
using (OleDbCommand cmd = new OleDbCommand(Commandstring, con)) {
try {
cmd.ExecuteNonQuery();
con.Close();
Debug.WriteLine("Connection to DB Terminated");
}
catch (Exception ex) {
Debug.WriteLine("Error Updating Database: " +ex.Message);
con.Close();
}
}
}
}
}
my exception message is saying there is an Syntax error in my Update statement.
Sending the statement to Debug writeline i get:
UPDATE tbl_login SET Time='21' WHERE Username='Bob'
Time is a reserved word. Enclose it in square brackets like this:
UPDATE tbl_login SET [Time]='21' WHERE Username='Bob'
I also think you should switch to a parameter query. But the reserved word issue is the cause of your immediate problem, and will also be an issue in a parameter query.

must declare variable scalar

i have this code:
private void btGuardar_Click(object sender, EventArgs e)
{
if (txDescrip.Text.Trim().Equals("") == false && txPath.Text.Trim().Equals("") == false)
{
try
{
byte[] imgData = getMyFileBytes(txPath.Text);
//Server connection
OleDbConnection connection = new OleDbConnection(strcx);
String q = "INSERT INTO MisImagenes (Id,CustomImage) values(#MyPath, #ImageData)";
//Initialize sql command object for insert
OleDbCommand command = new OleDbCommand(q, connection);
//We are passing original image path and image byte data as sql parameters
OleDbParameter pMyPath = new OleDbParameter("#MyPath", (object)txPath.Text);
OleDbParameter pImgData = new OleDbParameter("#ImageData", (object)imgData);
command.Parameters.Add(pMyPath);
command.Parameters.Add(pImgData);
//Open connection and execute insert query
connection.Open();
command.ExecuteNonQuery();
connection.Close();
Mensaje.aviso("Imagen Guardada :)");
//Limpiamos
clearAlta();
}
catch (Exception exc)
{
Mensaje.aviso("Something went wrong! :( " + exc.Message);
}
}
}
when i execute this says "Must declare the scalar variable "#MyPath"." ... any help? please, thank you.
I'm just trying to save an image to my sqlserver db by selecting the path and id description for the image. and i just get this frustrating error
you should use '?' instead of parameter names in oledb queries
INSERT INTO MisImagenes (Id,CustomImage) values(?, ?)
similar question and answer: OleDbCommand parameters order and priority