C#: SQL can't execute the reading - c#

I've ordered SQL Server from Somee. I want to use this SQL Server for my windows form. Somehow, i'm not sure, but whenever i execute the login query what i've found, it will have an unhandled exeption.
private void log_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection();
con.ConnectionString = "workstation id=wbhandler.mssql.somee.com;packet size=4096;user id=acc;pwd=pw;data source=wbhandler.mssql.somee.com;persist security info=False;initial catalog=wbhandler";
con.Open();
string felh = username.Text;
string jelsz = password.Text;
string query = "SELECT * FROM accounts WHERE account=#felhasznalo AND password=#jelszó";
SqlCommand cmd = new SqlCommand(query, con);
cmd.Parameters.Add(new SqlParameter("#felhasznalo", felh));
cmd.Parameters.Add(new SqlParameter("#jelszó", jelsz));
SqlDataReader dr = cmd.ExecuteReader();
if (dr.HasRows == true )
{
MessageBox.Show("Succes");
}
else
{
MessageBox.Show("Failed");
}
}
I thought that the adress is wrong, but then i found on the website the connection string, and now i don't really know.
I'm thinking what's the problem is.
I have 3 schemes in the sql:
dbo, acc, guest.
I first created a table in dbo, then in acc. Now in both of it. But it doesn't execute the SqlDataReader dr = cmd.ExecuteReader();, sadly. Like i said, it has unhandled exeption. Any solution? Any ideas?
(the acc scheme is an example what i created in somee, so it doesn't exist, it's fake)
I also tried this way:
using (var dr = cmd.ExecuteReader())
{
if (dr.HasRows)
{
MessageBox.Show("Sikeres Login!");
}
else
{
MessageBox.Show("Sikertelen Login");
}
}
The problem is always the ExecuteReader()

Try the SqlParameterCollection.AddWithValue Method instead:
cmd.Parameters.AddWithValue("#felhasznalo", felh);
cmd.Parameters.AddWithValue("#jelszó", jelsz);
I will also recommend that you use using statements on your SQL objects to ensure that the unmanaged resources they consume are freed when they are no longer needed. You can read more on the using statement from here.
Another thing that I can suggest is adding Charset=utf8; to your connection string.

Related

unable to insert data in sql database with c# even no error accur

hy I want to insert new record in my database but am unable to do this even code is fully error free, I added following code in my button click event
here is my code
SqlConnection con= new SqlConnection("Data Source=.;Initial Catalog=Sample;Integrated Security=true;");
SqlCommand cmd;
SqlDataAdapter adapt;
private void btn_Update_Click(object sender, EventArgs e)
{
string query="insert into users(Name,Password)values('ubaid','ali')";
cmd = new SqlCommand(query, con);
con.Open();
cmd.ExecuteNonQuery();
MessageBox.Show("Record Updated Successfully");
con.Close();
}
I mean insert query is not updating my database, even when I execute my query it return 2 not 0 which means query applied successfully,
not really an answer but the steps you need to take to see whats going on, so we can help you are a bit longer...
you will need to execute the following query, once in your sql management studio, and once in your program ... i suspect the result being different in both cases
select ##SERVERNAME, ##SERVICENAME, db_name(), SCHEMA_NAME()
on the code side please use this:
private void btn_Update_Click(object sender, EventArgs e)
{
// string query="insert into users(Name,Password)values('ubaid','ali')";
// cmd = new SqlCommand(query, con);
// con.Open();
// cmd.ExecuteNonQuery();
// MessageBox.Show("Record Updated Successfully");
// con.Close();
string query="select ##SERVERNAME, ##SERVICENAME, db_name(), SCHEMA_NAME()";
cmd = new SqlCommand(query, con);
con.Open();
using(var rdr = cmd.ExecuteReader())
{
rdr.read();
MessageBox.Show($"{rdr.GetString(0)}, {rdr.GetString(1)}, {rdr.GetString(2)}, {rdr.GetString(3)} ");
}
con.Close();
}
the result should show the name of the server, its instance name, the name of your DB and of the default schema you are using in both cases
example result for my testmachine would look like this:
srv9, MSSQLSERVER, testdb, dbo
expectation in your case:
you will get 2 different results which means that your sql management studio, where you are trying to check if your code did the right thing, is using a different server, instance, database or schema
with the provided information it will be possible to change the used connectionstring so both your clients work on the same database...

Cant read from SQL Server database in C#

I am currently working on a college assignment in which I am having trouble reading data from a SQL Server database. I'm attempting to read the Dentist Name column and then add these names to a combobox.
However when I input the column name it shows an error.
My table is called dentistInfo with columns Dentist ID, Dentist Name, Dentist Surname, DOB and Gender.
Eventually when I get to the reading done correctly I will then hopefully be able to populate their details when the names are selected from the combobox.
public partial class Dentist_Info : Form
{
Surgery mySurgery = new Surgery();
private SqlConnection conn;
private SqlCommand cmd;
private SqlDataAdapter da;
Surgery _formsSurgery;
public Dentist_Info(Surgery SurgeryToDisplay)
{
_formsSurgery = SurgeryToDisplay;
}
public void FillCombo()
{
SqlConnection conn = new SqlConnection(#"Data Source = GGJG; Initial Catalog = DentistDB; Integrated Security = True");
SqlCommand SelectCommand = new SqlCommand("SELECT * FROM DentistInfo", conn);
SqlDataReader myreader;
conn.Open();
try
{
myreader = SelectCommand.ExecuteReader();
while (myreader.Read())
{
string dname = myreader.GetString("Dentist Name");
comboBox1.Items.Add(dname);
}
conn.Close();
}
catch (Exception ex)
{
throw new Exception(ex.Message, ex);
}
finally
{
if (conn != null)
{
conn.Close();
}
}
}
Pro-tip: If you want to ask about an error, post the error.
In any case, the problem is easy to spot in this case. There's no overload of GetString that accepts a string as an argument - you can only use the column index.
So either you need to pass the column index (myreader.GetOrdinal("Dentist Name")) or you need to use the indexer ((string)myreader["Dentist Name"]). In either case, make sure to handle possible NULL values properly - data reader simply throws an exception if you try to read an SQL NULL value.
As an aside, your try...catch can be simplified (and more useful):
When you want to rethrow an exception, use throw; (no "argument"). Wrap the exception only if you have some information to add.
The catch clause isn't required. It seems that you're only using it for the finally - it's perfectly fine to just use try...finally without the catch.
conn can never be null in the finally clause - your try isn't long enough.
For a pattern like this, you want to use using instead of try...finally anyway. You should also use using for the data reader.
Try this: I recommend you putting [] in the Dentist Name since it has a space between the two words, which might cause you the error, or change the name from the Database to DentistName
public void FillCombo()
{
SqlConnection conn = new SqlConnection(#"Data Source = GGJG; Initial Catalog = DentistDB; Integrated Security = True");
SqlCommand SelectCommand = new SqlCommand("SELECT * FROM DentistInfo", conn);
conn.Open();
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter(SelectCommand);
da.fill(ds);
foreach(DataRow dr in ds.Tables[0].Rows)
{
comboBox1.Items.Add(dr["[Dentist Name]"].ToString());
}
conn.Close();
}
As per addition instead of using conn.Open() and conn.Close(), as the answer of the first user you can surround the connection inside a using like so:
using(SqlConnection conn = new SqlConnection(#"Data Source = GGJG; Initial Catalog = DentistDB; Integrated Security = True"))
{
//your codes here no need for conn.Open() and conn.Close()
}

ADO.Net c# 0x80131904 must declare scalar variable/function

I'm trying to use a function via a SQL connection I've done everywhere else in my application (only here it give the error, not the rest of the application). When i searched for what that error code meant the responses i found say it's an error when one can't connect to SQL server? but it doesn't give a solution.
here is my c# code
SqlConnection connection = Database.GetConnection();
DataTable dt = new DataTable("CRC");
SqlCommand cmd = new SqlCommand("SELECT dbo.CalcRentalCharge(#RentalStartDateTime,#RentalEndDateTime,#CarTypeID)", connection);
try
{
connection.Open();
using (SqlDataReader dr = cmd.ExecuteReader())
{
cmd.CommandType = CommandType.Text;
cmd.Parameters.Add("#RentalStartDateTimetext", SqlDbType.DateTime).Value = RentalStartDateTimeBox.Text;
cmd.Parameters.Add("#RentalEndDateTimetext", SqlDbType.DateTime).Value = RentalEndDateTimeBox.Text;
cmd.Parameters.Add("#CarTypeIDtext", SqlDbType.Int).Value = CarTypeID.Text;
connection.Open();
Decimal rentalChange = (Decimal)cmd.ExecuteScalar();
connection.Close();
MessageBox.Show("The rental change is: " + rentalChange.ToString());
if (dr.HasRows)
{
dt.Load(dr);
dataGridView1.DataSource = dt;
}
}
connection.Close();
Can you help me get this FUNCTION to work?
Don't use cmd.ExecuteReader() before adding parameter to command object.
It gives error,
add parameter to command and then cmd.execureReader()
You have a copy/paste error in your variable name:
In the line
cmd.Parameters.Add("#RentalStartDateTimetext", SqlDbType.DateTime).Value = RentalStartDateTimeBox.Text;
the string
RentalStartDateTimetext
needs to be
RentalStartDateTime
In addition to that, because it will pop up as your next error: Your opening and closing of the connection is wrong. Use a using block for the connection as well and open it directly after the start of the block. You don't need to close it manually, the using-block will do that for you.

C# ASP.NET TSQL Code Behind Upgrade DB

I'm trying to upgrade the db from users' input, but it doesn't work...
I'm using this:
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(strcon);
SqlCommand cmd = new SqlCommand();
SqlCommand ncmd = new SqlCommand("Update Utenti Set Nome = #vnome where [Indirizzo E-Mail]=#vem", con);
ncmd.Parameters.AddWithValue("#vem", Session["[Indirizzo E-Mail]"].ToString());
ncmd.Parameters.AddWithValue("#vnome", TextBox2.Text);
ncmd.Connection = con;
con.Open();
ncmd.ExecuteNonQuery();
con.Close();
Label2.Text = "Dati aggiornati con successo!";
Response.Redirect("~/ModificaDati.aspx");
}
When I click on the button it show me the Label2 text, but in the database the "Nome" is not changed, why?
Thanks before for the answers ^^
I would change your method as below
if (Session["[Indirizzo E-Mail]"] != null &&
!string.IsNullOrEmpty(Session["[Indirizzo E-Mail]"].ToString()) &&
!string.IsNullOrEmpty(TextBox2.Text))
{
string vem = Session["[Indirizzo E-Mail]"].ToString();
using (var con = new SqlConnection(strcon))
using (var ncmd = new SqlCommand("Update Utenti Set Nome = #vnome where [Indirizzo E-Mail]=#vem", con))
{
con.Open();
ncmd.Parameters.AddWithValue("#vem", vem);
ncmd.Parameters.AddWithValue("#vnome", TextBox2.Text);
int rows = ncmd.ExecuteNonQuery();
Label2.Text = rows + " Dati aggiornati con successo!";
}
}
Response.Redirect("~/ModificaDati.aspx");
Added input validation, session values can be null, better to check before you update database
when you create SqlCommand you can give the connection, no need to set it again
make sure your SQL is valid
use using statements for disposable objects like SqlConnection, SqlCommand
Your code looks ok. Just make sure you check if SQL is correct as Damith already suggested.
Another thing I’s recommend is additionally validating your parameters for data type correctness before executing the query.
Using this approach you’ll probably avoid a lot of unnecessary exceptions and also be able to provide more user friendly messages. Of course this only applies if user input is non text type
//Data Type verification
DateTime tmp;
if (!DateTime.TryParse(Label2.Text.Trim(), out tmp))
{
//Show error message that this is not a correct data type
}
Open your connection first
con.Open();
ncmd.Connection = con;
Hope it helps

asp session proper usage and possible interface usage

the code i'm using is below. Is this the proper way to use Session? also how do I call companyID and userID to clarify, if i did Session. is it Session.Contents or Session.Keys? this is my first time using session, I know I use httpcontact.current.user to access most of this but i'm not sure how to access each part of the data.
Thanks!
MySqlConnection cn = new MySqlConnection("Server=localhost;Database=users; User=root;Password=00;");
cn.Open();
string storedProcedureName = "VLID";
MySqlCommand cmd = new MySqlCommand(storedProcedureName, cn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#userName", this.Login1.UserName);
cmd.Parameters.Add("#passwordID", this.Login1.Password);
MySqlDataReader dr = cmd.ExecuteReader();
if (dr.HasRows)
{
dr.Read();
string userID = dr["userID"].ToString();
string companyID = dr["CompanyID"].ToString();
string sessionID = Session.SessionID.ToString();
Session.Add(companyID, "companyID");
Session.Add(userID, "userID");
e.Authenticated = true;
Response.Redirect("index.html");
// Event Authenticate is true
}
You are calling Session.Add method a little backwards:
Session.Add takes a key and a value, in that order; therefore, on your code you want:
Session.Add("companyID",companyID );
Session.Add("userID",userID );
But instead, you could do this, too:
Session["companyID"]=companyID;
Session["userID"]=userID;
Then, whenever you need to retrieve the userID value that you stored previously, you can do:
string userID= Session["userID"] as string;
As a side note, I wouldn't mix data access code on the UI code as you are doing.
The code that gets the data from the database should be moved to the data access layer (DAL).
And when you instantiate a database connection, always enclose it in an using statement so that is properly disposed when it comes out of scope:
using(MySqlConnection cn = new MySqlConnection("Server=localhost;Database=users; User=root;Password=00;"))
{
cn.Open();
//rest of the code
}

Categories

Resources