Trying to retrieve parameter value from another class library - c#

I have created Member Maintenance Code in which I will retrieve the members ID,Name and all basic things
My code is as follows:
private void Mem_Maintenance_Load(object sender, EventArgs e)
{
try
{
txt_mem_id.Text = Generate_no.gen_no("MEM").ToString();
}
catch(Exception Ex)
{
MessageBox.Show("Error\n\n"+Ex.ToString());
}
}
I have created a ClassLibrary named Library Whose code is as follows
namespace LIBRARY
{
public class Generate_no
{
public static int gen_no(string P_PRM_TYPE)
{ OleDbConnection connection = new OleDbConnection();
connection.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=E:\arekh\MS Access\soc_data.accdb;Persist Security Info=False;";
connection.Open();
int v_last_no = 0;
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
string query = #"select PARM_VALUE from soc_parm_mast where PARM_TYPE = '" + P_PRM_TYPE + "';";
command.CommandText = query;
OleDbDataReader reader = command.ExecuteReader();
reader.Read();
v_last_no = Int32.Parse(reader["PARM_VALUE"].ToString()) + 1;
reader.Close();
command.CommandText = #"update soc_parm_mast set PARM_VALUE = PARM_VALUE+1 where PARM_TYPE = " + P_PRM_TYPE + ";";
command.ExecuteNonQuery();
connection.Close();
return v_last_no;
}
}
}
But during execution an error is coming up
System.FormatException:Input string was not incorrect format at
LIBRARY.Generate_no.gen_no(String P_PRM_TYPE)

command.CommandText = #"update soc_parm_mast set PARM_VALUE = PARM_VALUE+1 where PARM_TYPE = '" + P_PRM_TYPE + "';";
You were missing the single quotation marks in the update statement

The Line v_last_no = Int32.Parse(reader["PARM_VALUE"].ToString()) + 1; causing the specified Error, The Int32.Parse will throw FormatException if the input is not convertible. So i strongly advise you to use Int32.TryParse(). Then the code will be like the following:
public static int gen_no(string P_PRM_TYPE)
{
using (OleDbConnection connection = new OleDbConnection(#"Connection string here"))
{
connection.Open();
int v_last_no = 0;
using (OleDbCommand command = new OleDbCommand())
{
command.Connection = connection;
string query = #"select PARM_VALUE from soc_parm_mast where PARM_TYPE = #P_PRM_TYPE";
command.CommandText = query;
command.Parameters.AddWithValue("#P_PRM_TYPE", P_PRM_TYPE);
OleDbDataReader reader = command.ExecuteReader();
reader.Read();
if (!Int32.TryParse(reader["PARM_VALUE"].ToString(), out v_last_no))
{
// Conversion failed, Show message if needed
// v_last_no will be 0
}
reader.Close();
}
using (OleDbCommand command = new OleDbCommand())
{
command.CommandText = #"update soc_parm_mast set PARM_VALUE = PARM_VALUE+1 where PARM_TYPE =#P_PRM_TYPE";
command.Parameters.AddWithValue("#P_PRM_TYPE", P_PRM_TYPE);
command.ExecuteNonQuery();
}
}
return v_last_no;
}
One more advise for you : beware of SQL Injection while using the Concatenated string as queries. Use parameterized queries instead.

Related

Populating textbox from after selecting value from comboBox

I am trying to populate my textbox after selecting a value from my comboBox.
My code is running fine, I don't have any errors when I run it but when I select a value from my comboBox, it's not populating my textbox. See my code below.
private OleDbConnection connection = new OleDbConnection();
public Form1()
{
InitializeComponent();
connection.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\ASUS\Documents\appointment2.accdb";
}
private void Lastname_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
connection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
OleDbDataReader reader = command.ExecuteReader();
while (reader.Read())
{
string query = "select * from appointments where patientNo = '" + Lastname.Text + "' ";
command.CommandText = query;
Firstname.Text = reader["firstName"].ToString();
patientNum.Text = reader["patientNo"].ToString();
contactNum.Text = reader["contactNo"].ToString();
}
connection.Close();
}
catch (Exception ex)
{
MessageBox.Show("Error" + ex);
}
}
Two immediate issues that I see:
You are populating the CommandText property of the OleDbCommand object after issuing the ExecuteReader method, meaning there is no SQL statement being evaluated.
The SQL statement should be populated before the ExecuteReader method is issued, i.e.:
connection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
command.CommandText = "select * from appointments where patientNo = '" + Lastname.Text + "' ";
OleDbDataReader reader = command.ExecuteReader();
while (reader.Read())
{
Firstname.Text = reader["firstName"].ToString();
patientNum.Text = reader["patientNo"].ToString();
contactNum.Text = reader["contactNo"].ToString();
}
connection.Close();
The where clause of your SQL statement assumes that patientNo contains string data, which could be incorrect given the name of this field.
Just found out the issue. Had the wrong value to compare my Lastname.Text with and fixed the code's arrangement. Thanks for all your help everyone.
connection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
command.CommandText = "select * from appointments where lastName = '" + Lastname.Text + "' ";
OleDbDataReader reader = command.ExecuteReader();
while (reader.Read())
{
Firstname.Text = reader["firstName"].ToString();
patientNum.Text = reader["patientNo"].ToString();
contactNum.Text = reader["contactNo"].ToString();
}
connection.Close();

C# and Oracle, login Form: Operation is not valid due to the current state of the object

private void bLogIn(object sender, EventArgs e)
{
string logging = "select * from CLIENT where LOGIN='" + this.t_Login.Text + "' and PASSWORD='" + this.t_Password.Text + "' ;";
OracleConnection conn = new OracleConnection("Data Source=XXX/orcl;User Id=XXX;Password=XXX;");
OracleCommand cmd = new OracleCommand();
cmd.CommandText = logging;
cmd.Connection = conn;
try
{
conn.Open();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
int count = 0;
OracleDataReader reader = cmd.ExecuteReader(); // At this line there is the error: Operation is not valid due to the current state of the object
while (reader.Read())
{
count = count + 1;
}
if (count == 1)
{
MessageBox.Show("Welcome");
}
else
{
MessageBox.Show("Wrong Password");
}
conn.Dispose();
}
This is code that was working for MySQL, but after conversion to Oracle it's not working. What am I doing wrong? Where's the difference. It should be so easy as in MySQL, right?
Why "OracleDataReader reader = cmd.ExecuteReader();" causes error: "Operation is not valid due to the current state of the object" ???
You are not assingning the connection to cmd.. try code below
OracleCommand cmd = new OracleCommand();
cmd.connection = conn;
cmd.CommandText = logging;
int count = 0;
OracleDataReader reader = cmd.ExecuteReader();

Value didn't double

I have error in this code. What should happen is if I have two stall in the database, the stall price must be doubled, but what happened in this code is if I have two stall in the database, the stall price isn't doubled and if I only have one stall the stall price is 0.
public double GetStallPrice(int commtaxno)
{
try
{
string query = "SELECT * FROM contract_details WHERE comm_tax_no = " + commtaxno;
DatabaseString myConnectionString = new DatabaseString();
OleDbConnection connection = new OleDbConnection();
connection.ConnectionString = myConnectionString.connect();
connection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
command.CommandText = query;
OleDbDataReader stallReader = command.ExecuteReader();
stallReader.Read();
while(stallReader.Read())
{
try
{
string query2 = "SELECT section_ID FROM specific_stall WHERE stall_no = '" + stallReader["stall_no"].ToString() + "'";
OleDbCommand command2 = new OleDbCommand();
command2.Connection = connection;
command2.CommandText = query2;
OleDbDataReader sectionReader = command2.ExecuteReader();
sectionReader.Read();
sectionid = Convert.ToInt32(sectionReader["section_ID"].ToString());
try
{
string query3 = "SELECT stall_price FROM stall_sections WHERE section_ID = " + sectionid;
OleDbCommand command3 = new OleDbCommand();
command3.Connection = connection;
command3.CommandText = query3;
OleDbDataReader stallPriceReader = command3.ExecuteReader();
stallPriceReader.Read();
stall_price = Convert.ToDouble(stallPriceReader["stall_price"].ToString());
}
catch (Exception c)
{
MessageBox.Show(c.GetBaseException().ToString());
}
}
catch (Exception b)
{
MessageBox.Show(b.GetBaseException().ToString());
}
sum_stall_price = sum_stall_price + stall_price;
}
connection.Close();
}
catch (Exception a)
{
MessageBox.Show(a.GetBaseException().ToString());
}
return sum_stall_price;
}
I think the error is here:
stallReader.Read();
while(stallReader.Read())
You read first record and then read the second, without processing the first.
You have to remove first row and leave just
while(stallReader.Read())
As a side note, you should try to always use using syntax with classes that implement IDisposable interface. So, just an example:
using (OleDbConnection connection = new OleDbConnection())
{
// All the code inside
}
In this way you're sure that the object is properly released.
Finally: do not compose queries manually, but use parameters instead!!
Using parameters can avoid SQL injection and many headaches due to numeric (float, double, currency) and dates conversion!!

How to apply National Character set to dynamic query

I am trying to apply N before variable name for Unicode as mentioned in How to use 'LIKE' statement with unicode strings?
With the following code I am getting following error. What need to be corrected here?
Exception: Invalid column name 'N#input'.
string commandText = #"SELECT AccountType,*
FROM Account
WHERE AccountType LIKE N#input ";
CODE
static void Main(string[] args)
{
string result = DisplayTest("Daily Tax Updates: ----------------- Transactions");
}
private static string DisplayTest(string searchValue)
{
string test = String.Empty;
string connectionString = "Data Source=.;Initial Catalog=LibraryReservationSystem;Integrated Security=True;Connect Timeout=30";
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
string commandText = #"SELECT AccountType,*
FROM Account
WHERE AccountType LIKE N#input ";
using (SqlCommand command = new SqlCommand(commandText, connection))
{
command.CommandType = System.Data.CommandType.Text;
command.Parameters.AddWithValue("#input", "%" + searchValue + "%");
using (SqlDataReader reader = command.ExecuteReader())
{
if (reader.HasRows)
{
while (reader.Read())
{
test = reader.GetString(0);
}
}
}
}
}
return test;
}
I see a few issues.
string commandText = #"SELECT AccountType,*
FROM Account
WHERE AccountType LIKE N#input";
should be
string commandText = #"SELECT AccountType,*
FROM Account
WHERE AccountType LIKE #input";
...
command.Parameters.Add("#input",System.Data.SqlDbType.NVarChar,<<size>>);
command.Parameters[0].Value = "%" + searchValue + "%";
I see you're trying to use a nvarchar parameter. I think .net does that by default with .AddWithValue
I'm not sure why do you need the typecast to nvarchar, you should be fine without the 'N' part.
That part you need when you want to specify that a string literal should be treated as nvarchar not as varchar, as in SELECT * from Table where field like N'%VALUE%'
Otherwise, you just declare your variable/parameter as nvarchar
Taken from this stack Stack overflow
SqlParameter parameter = new SqlParameter();
parameter.ParameterName = "#CategoryName";
parameter.SqlDbType = SqlDbType.NVarChar;
parameter.Direction = ParameterDirection.Input;
parameter.Value = categoryName;
Try this one -
private static string DisplayTest(string searchValue)
{
string connectionString = "Data Source=.;Initial Catalog=LibraryReservationSystem;Integrated Security=True;Connect Timeout=30";
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
string commandText = #"SELECT AccountType,* FROM Account WHERE AccountType LIKE #input";
using (SqlCommand command = new SqlCommand(commandText, connection))
{
command.CommandType = System.Data.CommandType.Text;
command.Parameters.Add("#input", SqlDbType.NVarChar);
command.Parameters["#input"].Value = string.Format("%{0}%", searchValue);
using (SqlDataReader reader = command.ExecuteReader())
{
if (reader.HasRows)
{
while (reader.Read())
{
return reader.GetString(0);
}
}
}
}
}
return String.Empty;
}

How to run multiple SQL commands in a single SQL connection?

I am creating a project in which I need to run 2-3 SQL commands in a single SQL connection.
Here is the code I have written:
SqlConnection con = new SqlConnection(#"Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\project.mdf;Integrated Security=True");
con.Open();
SqlCommand cmd = new SqlCommand("select * from " + mytags.Text + " ", con);
SqlDataReader rd = cmd.ExecuteReader();
if (rd.Read())
{
con.Close();
con.Open();
SqlCommand cmd1 = new SqlCommand("insert into " + mytags.Text + " values ('fname.lname#gmail.com','" + TextBox3.Text + "','" + TextBox4.Text + "','" + TextBox5.Text + "','"+mytags.Text+"')", con);
cmd1.ExecuteNonQuery();
label.Visible = true;
label.Text = "Date read and inserted";
}
else
{
con.Close();
con.Open();
SqlCommand cmd2 = new SqlCommand("create table " + mytags.Text + " ( session VARCHAR(MAX) , Price int , Description VARCHAR(MAX), Date VARCHAR(20),tag VARCHAR(10))", con);
cmd2.ExecuteNonQuery();
con.Close();
con.Open();
SqlCommand cmd3 = new SqlCommand("insert into " + mytags.Text + " values ('" + Session + "','" + TextBox3.Text + "','" + TextBox4.Text + "','" + TextBox5.Text + "','" + mytags.Text + "')", con);
cmd3.ExecuteNonQuery();
label.Visible = true;
label.Text = "tabel created";
con.Close();
}
I have tried to remove the error and I got that the connection is not going to else condition. Please review the code and suggest if there is any mistake or any other solution for this.
Just change the SqlCommand.CommandText instead of creating a new SqlCommand every time. There is no need to close and reopen the connection.
// Create the first command and execute
var command = new SqlCommand("<SQL Command>", myConnection);
var reader = command.ExecuteReader();
// Change the SQL Command and execute
command.CommandText = "<New SQL Command>";
command.ExecuteNonQuery();
The following should work. Keep single connection open all time, and just create new commands and execute them.
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
using (SqlCommand command1 = new SqlCommand(commandText1, connection))
{
}
using (SqlCommand command2 = new SqlCommand(commandText2, connection))
{
}
// etc
}
Just enable this property in your connection string:
sqb.MultipleActiveResultSets = true;
This property allows one open connection for multiple datareaders.
I have not tested , but what the main idea is: put semicolon on each query.
SqlConnection connection = new SqlConnection();
SqlCommand command = new SqlCommand();
connection.ConnectionString = connectionString; // put your connection string
command.CommandText = #"
update table
set somecol = somevalue;
insert into someTable values(1,'test');";
command.CommandType = CommandType.Text;
command.Connection = connection;
try
{
connection.Open();
}
finally
{
command.Dispose();
connection.Dispose();
}
Update:
you can follow
Is it possible to have multiple SQL instructions in a ADO.NET Command.CommandText property? too
This is likely to be attacked via SQL injection by the way. It'd be worth while reading up on that and adjusting your queries accordingly.
Maybe look at even creating a stored proc for this and using something like sp_executesql which can provide some protection against this when dynamic sql is a requirement (ie. unknown table names etc). For more info, check out this link.
No one has mentioned this, but you can also separate your commands using a ; semicolon in the same CommandText:
using (SqlConnection conn = new SqlConnection(connString))
{
using (SqlCommand comm = new SqlCommand())
{
comm.Connection = conn;
comm.CommandText = #"update table ... where myparam=#myparam1 ; " +
"update table ... where myparam=#myparam2 ";
comm.Parameters.AddWithValue("#myparam1", myparam1);
comm.Parameters.AddWithValue("#myparam2", myparam2);
conn.Open();
comm.ExecuteNonQuery();
}
}
Multiple Non-query example if anyone is interested.
using (OdbcConnection DbConnection = new OdbcConnection("ConnectionString"))
{
DbConnection.Open();
using (OdbcCommand DbCommand = DbConnection.CreateCommand())
{
DbCommand.CommandText = "INSERT...";
DbCommand.Parameters.Add("#Name", OdbcType.Text, 20).Value = "name";
DbCommand.ExecuteNonQuery();
DbCommand.Parameters.Clear();
DbCommand.Parameters.Add("#Name", OdbcType.Text, 20).Value = "name2";
DbCommand.ExecuteNonQuery();
}
}
Here you can find Postgre example, this code run multiple sql commands (update 2 columns) within single SQL connection
public static class SQLTest
{
public static void NpgsqlCommand()
{
using (NpgsqlConnection connection = new NpgsqlConnection("Server = ; Port = ; User Id = ; " + "Password = ; Database = ;"))
{
NpgsqlCommand command1 = new NpgsqlCommand("update xy set xw = 'a' WHERE aa='bb'", connection);
NpgsqlCommand command2 = new NpgsqlCommand("update xy set xw = 'b' where bb = 'cc'", connection);
command1.Connection.Open();
command1.ExecuteNonQuery();
command2.ExecuteNonQuery();
command2.Connection.Close();
}
}
}
using (var connection = new SqlConnection("Enter Your Connection String"))
{
connection.Open();
using (var command = connection.CreateCommand())
{
command.CommandText = "Enter the First Command Here";
command.ExecuteNonQuery();
command.CommandText = "Enter Second Comand Here";
command.ExecuteNonQuery();
//Similarly You can Add Multiple
}
}
It worked for me.

Categories