How to make auto generate number for text box in C# - c#

I want to Insert auto generate number show in textbox when form is loaded (like 000000001) in database that not define primary key and if table number found 0 then it increment every time when form open by user to entry data. Please help me how to do it. I am using C#.
Thanks
its working , but I need to from table filed.
public void RetriveWorkRequestNo ()
{
try
{
string query = "SELECT IDENT_CURRENT('WorkRequests')";
if (conn.State == ConnectionState.Closed)
{
conn.Open();
}
SqlCommand cmdwr = new SqlCommand(query, conn);
SqlDataReader reader = cmdwr.ExecuteReader();
while (reader.Read())
{
int value = int.Parse(reader[0].ToString()) + 1;
textWorkRequestNo.Text = value.ToString("0000000000");
textWorkRequestNo.ReadOnly = true;
}
}
catch (Exception)
{
throw;
}
finally
{
if (conn.State == ConnectionState.Open)
{
conn.Close();
}
}

Finally I have done it using Sequence in MS SQL Server 2012
private int RetriveWorkRequestID()
{
try
{
string query = "SELECT NEXT VALUE FOR sqWorkRequests";
if (conn.State == ConnectionState.Closed)
{
conn.Open();
}
using (SqlCommand cmd = new SqlCommand(query, conn))
{
using (SqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
int value = int.Parse(reader[0].ToString());
string date = DateTime.Now.ToString("yyMM");
WorkRequestID = Convert.ToInt32(date.ToString() + value.ToString("000"));
}
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
finally
{
if (conn.State == ConnectionState.Open)
{
conn.Close();
}
}
return WorkRequestsID;
}

Related

C# closing mysql connection is not working, mysqli_connect(): (08004/1040): Too many connections

I'm getting this error on phpMyAdmin
mysqli_connect(): (08004/1040): Too many connections
The only script that is using this DB:
public static bool checkIp(string ip)
{
Console.WriteLine("CHECKIP");
try
{
string sql = " SELECT * FROM `Ip tables` ";
MySqlConnection con = new MySqlConnection("host=hostname;user=username;password=password;database=database;");
MySqlCommand cmd = new MySqlCommand(sql, con);
con.Open();
MySqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
if (ip == reader.GetString("Ip"))
{
Console.WriteLine("Benvenuto, " + reader.GetString("Name"));
con.Close();
return true;
}
}
con.Close();
return false;
}
catch(SqlException exp)
{
throw new InvalidOperationException("Error", exp);
}
}
Does this code close the connection correctly or something is wrong?
EDIT:
I added this block after the catch block
finally
{
if(con.State == System.Data.ConnectionState.Open)
{
con.Close();
}
}
Any better way to write the code? Would finaly block still run if return is executed?
You should put your query in a using statement like this:
string conString= "host=hostname;user=username;password=password;database=database;"
using (MySqlConnection con = new MySqlConnection(conString))
{
con.Open();
using (MySqlCommand com = con.CreateCommand())
{
com.CommandText = "SELECT * FROM `Ip tables`";
using (MySqlDataReader dr = com.ExecuteReader())
{
while (reader.Read())
{
if (ip == reader.GetString("Ip"))
{
Console.WriteLine("Benvenuto, " + reader.GetString("Name"));
con.Close();
return true;
}
}
}
}
}
This will automatically close the connection without having to state con.Close()

Get Value of specific Column while Login (C# Mysql)

I am trying to make a login at the moment. I watched some videos and found a good way. Every user has an id, Username and Password. I want to get the id of the user who has just been logged in and save it in an Integer. I also tried it with an ExecuteReader but I get an Exception(MySql.Data.MySqlClient.MySqlException).
My current Code is:
try
{
if (sqlCon.State == ConnectionState.Closed)
{
sqlCon.Open();
}
string query = "SELECT COUNT(1) FROM Users_Table WHERE Username=#Username AND Password=#Password;";
MySqlCommand sqlCmd = new MySqlCommand(query, sqlCon);
sqlCmd.Parameters.AddWithValue("#Username", maintxtbox1.Text);
sqlCmd.Parameters.AddWithValue("#Password", Hashed_Password);
int count = Convert.ToInt32(sqlCmd.ExecuteScalar());
if (count == 1)
{
//Login correct
}
else
{
//Login incorrect
}
}
catch
{
//Exception
}
finally
{
sqlCon.Close();
}
The try with the ExecuteReader:
try
{
if (sqlCon.State == ConnectionState.Closed)
{
sqlCon.Open();
}
string query = "SELECT id,Username,Password FROM Users_Table WHERE Username=#Username AND Password=#Password;";
MySqlCommand sqlCmd = new MySqlCommand(query, sqlCon);
sqlCmd.Parameters.AddWithValue("#Username", maintxtbox1.Text);
sqlCmd.Parameters.AddWithValue("#Password", Hashed_Password);
MySqlDataReader datareader = sqlCmd.ExecuteReader();
if (datareader.HasRows)
{
MessageBox.Show("Test: " + datareader.GetString("id"));
}
else
{
//Login incorrect
}
}
catch
{
//Exception
}
finally
{
sqlCon.Close();
}
I hope somebody can help me. Thank you in advance.
Try and use the Read method:
if(datareader.Read()){
MessageBox.Show("Test: "+datareader.GetString(0));
}
EDIT:
To make good use and disposal of resources I recommend using the MySqlDataReader inside a using block, e.j.
using(MySqlDataReader reader = new sqlCmd.ExecuteReader()){
if(reader.Read()){
MessageBox.Show("Test: "+reader.GetString(0));
}
}
I found a solution to my Question by myself. I forgot the while(datareader.Read()) in the ìf(datareader.HasRows) query. Here is my working Code:
try
{
if (sqlCon.State == ConnectionState.Closed)
{
sqlCon.Open();
}
string query = "SELECT * FROM Users_Table WHERE username=#Username AND password=#Password;";
MySqlCommand sqlCmd = new MySqlCommand(query, sqlCon);
sqlCmd.Parameters.AddWithValue("#Username", maintxtbox1.Text);
sqlCmd.Parameters.AddWithValue("#Password", Hashed_Password);
MySqlDataReader datareader = sqlCmd.ExecuteReader();
if (datareader.HasRows)
{
while (datareader.Read())
{
UserID = datareader.GetInt32("id");
}
}
else
{
//Incorrect Password
}
}
catch
{
//Error
}
finally
{
sqlCon.Close();
}

While more query executing, i got "Not allowed to change the 'ConnectionString' property."

class CommonConnection
{
public class dStructure
{
public static string ConnectionString = "";
}
public SqlConnection Conn;
#region "Connection Procedures"
public string ConnectionString
{
get
{
string sConn = string.Empty;
sConn = #"Server=ServerName;Initial Catalog=Database;User ID=userid;Password=password;";
dStructure.ConnectionString = sConn;
return dStructure.ConnectionString;
}
}
public void cnOpen()
{
try
{
if (Conn == null)
{
Conn = new System.Data.SqlClient.SqlConnection();
}
if (Conn.State == ConnectionState.Open)
{
Conn.Close();
}
Conn.ConnectionString = ConnectionString;
Conn.Open();
}
catch (SqlException e)
{
SqlConnection.ClearAllPools();
throw e;
}
catch (Exception ex)
{
throw ex;
}
}
public void cnClose()
{
try
{
if ((Conn != null))
{
if (Conn.State == ConnectionState.Open)
{
Conn.Close();
}
}
}
catch (Exception ex)
{
throw ex;
}
finally
{
Conn = null;
}
}
#endregion
public int ExecuteQuery(string strQuery, Int16 TimeOut = 30)
{
int RecordsAffected;
SqlCommand cmd;
try
{
cnOpen();
cmd = new SqlCommand(strQuery, Conn);
cmd.CommandTimeout = TimeOut;
RecordsAffected = cmd.ExecuteNonQuery();
return RecordsAffected;
}
catch (Exception ex)
{
throw ex;
}
finally
{
cnClose();
cmd = null;
}
}
}
// Tried another option like below,
public int ExecuteQuery(string strQuery, short TimeOut = 10)
{
SqlConnection NewConn = new SqlConnection();
try
{
if (NewConn == null)
{
NewConn = new System.Data.SqlClient.SqlConnection();
}
if (NewConn.State == ConnectionState.Open)
{
NewConn.Close();
}
NewConn.ConnectionString = "Server=ServerName;Initial Catalog=Database;User ID=userid;Password=password;";
NewConn.Open();
return new SqlCommand(strQuery, NewConn)
{
CommandTimeout = ((int)TimeOut)
}.ExecuteNonQuery();
}
catch (Exception ex)
{
throw ex;
}
finally
{
NewConn.Close();
}
}
But still getting same issue.
Its desktop application, multi threaded. But while more query load on this, i'm getting Not allowed to change the 'ConnectionString' property. The connection's current state is open.
Note that not every time i get this issue, only when more query are executing.
// Update 2
As per suggested in another question, i tried with below code but problem remains same.
public int ExecuteQuery(string strQuery, short TimeOut = 10)
{
int executeReader = 0;
try
{
using (SqlConnection connection = new SqlConnection(#"Server=Server;Initial Catalog=DB;User ID=id;Password=Password;"))
{
try
{
connection.Open();
SqlCommand command = new SqlCommand(strQuery, connection);
command.CommandType = CommandType.Text;
command.CommandTimeout = TimeOut;
executeReader = command.ExecuteNonQuery();
}
catch (Exception ex)
{
throw ex;
}
}
return executeReader;
}
catch (Exception ex)
{
throw ex;
}
}
As suggested there, using command used default IDisposable so no need to close connection.
try this
Class:
public class CommonConnection
{
String constr = System.Configuration.ConfigurationManager.ConnectionStrings["myconectionstring"].ConnectionString;
public CommonConnection()
{
//
// TODO: Add constructor logic here
//
}
//Insert,Update,Delete....
public int ExecuteNonQuery1(string str)
{
//String constr = System.Configuration.ConfigurationManager.ConnectionStrings["CommonConnection"].ConnectionString;
SqlConnection con = new SqlConnection(constr);
SqlCommand cmd = new SqlCommand(str, con);
int result = 0;
try
{
con.Open();
result = cmd.ExecuteNonQuery();
con.Close();
}
catch (Exception ex)
{
result = -1;
try
{
if (con.State == ConnectionState.Open)
{
con.Close();
}
}
catch (Exception ex2)
{
// ErrHandler.WriteError(ex2.ToString());
}
// ErrHandler.WriteError(ex.ToString());
}
return result;
}
}
ASPX.CS:
SortedList s1 = new SortedList();
s1.Add("#mode", "Update");
s1.Add("#cid", ViewState["CategoryId"]);
int a = sp.ExecuteNonQuerySP1("SP_Name", s1);
if (a > 0)
{
}
In both of your code DEMO here is catch..
lets check this.
public void cnOpen()
{
try
{
if (Conn == null)
{
Conn = new System.Data.SqlClient.SqlConnection();
}
if (Conn.State == ConnectionState.Open)
{
Conn.Close();
}
Conn.ConnectionString = ConnectionString;
Conn.Open();
}`
Suppose if conn == null then it will go inside block and create new connection and everything is fine. but what if condition would be false, then it won't create new sqlConnection instance and it will move to second if condition
if (Conn.State == ConnectionState.Open)
{
Conn.Close();
}
Since you told when more query is executing, so it also may happen that state of connection would be anything except open like connecting, fetching, broken, etc so this if condition will be false if any of them happen except ConnectionState.Open and your existing connection will not closed and further it will go to next line where it will encounter
Conn.ConnectionString = ConnectionString;
If your connection is not closed then it will try to change existing connection's (SqlConnection instance) connection string. Which can't be change if instance is not disposed.So it will throw exception.
EDIT Try to do something like this and delete Conn.open() from this block of code.
if (Conn.State == ConnectionState.Open)
{
Conn.Close();
}
if (Conn == null)
{
Conn = new System.Data.SqlClient.SqlConnection();
Conn.ConnectionString = ConnectionString;
}
and one more thing which you need to update in public int ExecuteQuery(string strQuery, Int16 TimeOut = 30) in method. put this line Conn.Open(); after cmd.CommandTimeout = TimeOut;
public int ExecuteQuery(string strQuery, Int16 TimeOut = 30)
{
int RecordsAffected;
SqlCommand cmd;
try
{
cnOpen();
cmd = new SqlCommand(strQuery, Conn);
cmd.CommandTimeout = TimeOut;
Conn.Open(); //Add this here
RecordsAffected = cmd.ExecuteNonQuery();
return RecordsAffected;
}
catch (Exception ex)
{
throw ex;
}
finally
{
cnClose();
cmd = null;
}
}
}

ExecuteNonQuery() returns -1

For some reason result is always -1 and nothing get added to the database. I executed the query in SQL Server and it runs fine. I don't get any exception whatsoever and I don't use any stored procedure.
SqlConnection con = new SqlConnection("Data Source=.\\SQLEXPRESS;Initial Catalog=RAINBOW;Integrated Security=True");
SqlCommand cmd;
cmd = new SqlCommand("INSERT INTO ItemDetails.item(description,category_id) VALUES (#item_desc,#cat_id)", con);
cmd.Parameters.AddWithValue("#item_desc", txtitemdesc.Text);
cmd.Parameters.AddWithValue("#cat_id", GetCategoryID());
try
{
con.Open();
int result = cmd.ExecuteNonQuery();
if (result > 0)
{
MessageBox.Show("Record Inserted Successfully!");
}
else
{
MessageBox.Show("Failed to add record");
}
}
catch (SqlException ex)
{
MessageBox.Show("An error has occured! " + ex);
}
finally
{
con.Close();
}
Edit
int GetCategoryID()
{
int cat_id = 0;
cmd = new SqlCommand("SELECT category_id FROM ItemDetails.category WHERE category_desc=#cat_desc", con);
con.Open();
cmd.Parameters.AddWithValue("#cat_desc", cboCategory.Text);
reader = cmd.ExecuteReader();
while (reader.Read())
{
cat_id = int.Parse(reader["category_id"].ToString());
}
reader.Close();
con.Close();
return cat_id;
}
If possible then don't use AddWithValue(). Actually when you are not providing type explicitly, it will try to convert implicitly and sometimes the implicit conversion may not be the most optimal of conversions. You can find some more discussion in this link.
And most important thing is don't forget to clear parameters before assign, by using this line.
cmd.Parameters.Clears();
Check below code.
string sqlQuery = "INSERT INTO ItemDetails.item(description,category_id) VALUES (#item_desc,#cat_id)";
using (SqlCommand cmd = new SqlCommand(sqlQuery, con))
{
cmd.CommandType = CommandType.Text;
cmd.Parameters.Clears(); // Add this same line in your getcategory function.
cmd.Parameters.Add("#item_desc", SqlDbType.VarChar, 1000).Value = txtitemdesc.Text;
cmd.Parameters.Add("#cat_id", SqlDbType.Int).Value = GetCategoryID();
try
{
con.Open();
int result = cmd.ExecuteNonQuery();
if (result > 0)
{
MessageBox.Show("Record Inserted Successfully!");
}
else
{
MessageBox.Show("Failed to add record");
}
}
catch (SqlException ex)
{
MessageBox.Show("An error has occured! " + ex);
}
finally
{
con.Close();
}
}

How to handel Select,Update query on foreach loop?

SERVER A: public string connStr = "Data Source=PH-09-5336;Initial Catalog=InventoryDB;Integrated Security=True";
SERVER B: public string connWIP = "Data Source=PWODU-COGNOSDB3;Initial Catalog=BI_SOURCE;
I have this method of inserting records to InventoryDB.DBO.FG_FILLIN from excell file.
Select records from BI_SOURCE.dbo.ODU_WIP_PI then update the null records(item Number) on InventoryDB.DBO.FG_FILLIN if its serialnumber is match on BI_SOURCE.dbo.ODU_WIP_PI serialnumber.
Problems:
I have tried to updated 13000 of records and it takes 5 minutes to be updated.
I need to update the new inserted record InventoryDB.DBO.FG_FILLIN that has only itemnumber that have null records.
But in my code it loops and update again all records in InventoryDB.DBO.FG_FILLIN
I really stack in this problem.
-------------------------------------INSERT RECORDS----------------------------------------
using (SqlConnection conn = new SqlConnection(connStr))
{
using (SqlCommand cmd = new SqlCommand("Insert into dbo.FG_FILLIN Select * FROM OPENROWSET('Microsoft.Jet.OLEDB.4.0','Excel 8.0;Database=" + filepath1 + ";HDR=YES','SELECT * FROM [" + Sheetname1 + "$]')", conn))
{
try
{
conn.Open();
cmd.ExecuteNonQuery();
txtsheet1.Text = string.Empty;
txtpath1.Text = string.Empty;
txtpath1.Focus();
MessageBox.Show("FILL IN Mass Upload Success!");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
txtsheet1.Text = string.Empty;
txtpath1.Text = string.Empty;
txtpath1.Focus();
}
finally
{
if (conn.State == ConnectionState.Open) cmd.Connection.Close();
conn.Close();
}
}
---------------------------------SELECT UPDATE -----------------------------------
public void Update()
{
using (SqlConnection conn = new SqlConnection(connWIP))
{
try
{
conn.Open();
using (SqlDataAdapter dAd = new SqlDataAdapter("select WIP_serialNumber, WIP_ItemID from BI_SOURCE.dbo.ODU_WIP_PI", conn))
{
DataTable data = new DataTable();
dAd.Fill(data);
using (SqlConnection conn2 = new SqlConnection(connStr))
{
conn2.Open();
try
{
foreach (DataRow recordFromServerA in data.Rows)
{
using (SqlCommand dCmd = new SqlCommand("update [dbo].[FG_FILLIN] SET ItemNumber=#ItemNumber where SerialNumber=#SerialNumber", conn2))
{
dCmd.Parameters.AddWithValue("#ItemNumber", recordFromServerA["WIP_ItemAlias"]);
dCmd.Parameters.AddWithValue("#SerialNumber", recordFromServerA["WIP_serialNumber"]);
dCmd.ExecuteNonQuery();
}
}
}
catch (Exception ee)
{
MessageBox.Show(ee.Message);
}
finally
{
if (conn2.State == ConnectionState.Open) conn2.Close();
}
}
}
MessageBox.Show("All Records Updated Successfully!");
}
catch (Exception ee)
{
MessageBox.Show(ee.Message);
}
finally
{
if (conn.State == ConnectionState.Open) conn.Close();
}
}
}
#endregion
If I've understood your problem correctly you might be able to speed up the update process considerably by just executing a single SQL statement, rather than looping through each row individually.
How about this? After you've loaded your records into table A (FG_FILLIN), create an SQL UPDATE statement that uses a join from table A onto table B where the ItemNumber field in table A is null. Something like this should do it:
UPDATE [dbo].[FG_FILLIN]
SET ItemNumber = table2.WIP_ItemID
FROM [dbo].[FG_FILLIN] INNER JOIN BI_SOURCE.dbo.ODU_WIP_PI as table2
ON [dbo].[FG_FILLIN].SerialNumber = table2.WIP_SerialNumber
WHERE [dbo].[FG_FILLIN].ItemNumber IS NULL
another thing,
you could also wrap you stuff into a
using(var scope = new TransactionScope())
{
stuff
scope.Complete();
}
to make it a transaction

Categories

Resources