mysql datareader not finding rows c# - c#

I got a question about c# and mysql. I would like to make a very simpel login form that is connected to my local db. I got the connection to work (tested it) but i have a problem with reading my data that is returned from a select.
I'm trying to put an ID into a string so I can display it(this is just for testing). Now I have searched a lot on google and almost everyone has something like this. When I execute it doesn't give error but my sqldatareader finds nothing. In the first if I ask if it has got any rows and there are none.
What am I doing wrong? My username/password do exist in my db.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using MySql.Data.MySqlClient;
namespace eindwerk
{
public partial class LoginForm : Form
{
string myConnection = "Server=localhost;Database=mydb;Uid=root;Pwd=root;";
MySqlCommand cmd;
MySqlConnection connection;
public LoginForm()
{
InitializeComponent();
connection = new MySqlConnection(myConnection);
connection.Open();
}
private void loginForm_Load(object sender, EventArgs e)
{
this.Location = new Point((Screen.PrimaryScreen.WorkingArea.Width - this.Width) / 2,
(Screen.PrimaryScreen.WorkingArea.Height - this.Height) / 2);
}
private void btnLogin_Click(object sender, EventArgs e)
{
try
{
cmd = connection.CreateCommand();
cmd.CommandText = "SELECT idlogin FROM login WHERE (username='#username') AND (password='#password') LIMIT 1;";
cmd.Parameters.AddWithValue("#username", txtbxLoginUsername.Text);
cmd.Parameters.AddWithValue("#password", txtbxLoginPassword.Text);
MySqlDataReader rdr = cmd.ExecuteReader();
rdr.Read();
if (rdr.HasRows)
{
while (rdr.Read())
{
label1.Text = rdr.GetInt32("idlogin").ToString();
}
}
else
{
lblLoginError.Visible = true;
}
rdr.Close();
}
catch {
lblLoginError.Text = "Nope";
lblLoginError.Visible = true;
}
}
}
}

You are calling Read() Multiple time. Call the While(Reader.Read()) single time and check the result by if(rdr.HasRows()){} for check result is return or nothing is come in the response.

You are returning only 1 row, but you are calling Read() twice. Your row is effectively discarded before you look at your data.

After a long search i have found the problem ! In my sql query i put username='#username', there lies the problem. You can't use single quotes !!!. I removed the quotes and it works perfectly.
That is whay you get for trusthing a search result on the third page of google...
Thanks to all !

Related

how to solve exception for the connection string(local database c#)

ok so the first problem is the connection string itself it has this exception that i do not understand so i tried to put it in a try catch syntax but as i inserted it in the public partial class Form1 : Form the parenthesis are acting up so i inserted it in a function and now the fuction has this error:
Severity Code Description Project File Line Suppression State
Error CS0161 'Form1.connection()': not all code paths return a value Restaurant Management System C:\Users\admin\source\repos\Restaurant Management System\Restaurant Management System\Form1.cs 36 Active
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace Restaurant_Management_System
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
panel1.BackColor = Color.FromArgb(50, Color.Black);
label1.BackColor = Color.FromArgb(30, Color.Beige);
label2.BackColor = Color.FromArgb(0, Color.Black);
Password.BackColor = Color.FromArgb(0, Color.Black);
}
SqlCommand cmd;
SqlDataReader dr;
public SqlConnection connection()
{
try
{
SqlConnection con = new SqlConnection("Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename= \"|Data Directory|\\Coffee(LoginEmployee).mdf\";Integrated Security=True;");
}
catch (Exception ex)
{
MessageBox.Show("Error message: COULD NOT CONNECT STRING: " + ex);
}
}
private string getUsername()
{
SqlConnection con = connection();
cmd = new SqlCommand("SELECT nalue FROM EmployeeLog where Property=Username", con);
dr = cmd.ExecuteReader();
dr.Read();
return dr[0].ToString();
}
private string getPassword()
{
SqlConnection con = connection();
cmd = new SqlCommand("SELECT nalue FROM EmployeeLog where Property=Password", con);
dr = cmd.ExecuteReader();
dr.Read();
return dr[0].ToString();
}
What do i need to replace? why does it not all return a value? if i use the void case it will also have this error that i cannot explicitly convert it to sqlconnection. this is made in the latest visual studio 2017
If you catch the exception, no SqlConnection will be returned. So you could return null after showing the message box.
Then of course, you will need to do a null check after calling connection() so you don't get a null reference exception trying to use it.
You also need to return the connection you are creating:
return new SqlConnection("Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=|Data Directory|Coffee(LoginEmployee).mdf;Integrated Security=True;");
Note: I don't recommend hard-coding your connection string either! You would normally add the connection string to your app.config/web.config and read it using ConfigurationManager.ConnectionStrings... - this is because you might have different instance names on different machines, or you might want to point to a database on a server rather than local. You will not need to change the code and recompile just to make it work on more than one machine.
There is information on microsoft's class library site (https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnectionstringbuilder.attachdbfilename(v=vs.110).aspx) saying: An error will be generated if a log file exists in the same directory as the data file and the 'database' keyword is used when attaching the primary data file. In this case, remove the log file. Once the database is attached, a new log file will be automatically generated based on the physical path.

Visual C# SQL statement won't insert into database

I am trying to simply insert values into an SQL table. The ID in the database cannot be AUTO_INCREMENT so I use MAX and +1. Not only will this code not make a new ID, it simply isn't inserting anything into the table.
Even in the debugger there are no errors or warnings, it just isn't showing up in the database itself..
Here is my code:
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Windows;
using System.ComponentModel;
using System.Drawing;
using System.Text;
namespace WebApplication2
{
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void ButtonClick(object sender, EventArgs e){
using (var sqlConnection1 = new SqlConnection("Data
Source=SERVER; Initial Catalog = Metal; Integrated
Security = True"))
{
SqlDataAdapter cmd = new SqlDataAdapter();
using (var insertData = new SqlCommand("INSERT INTO ApptIn
(CONTROLNUMBER, CARRIERNAME, EXPECTEDNUMOFPIECES, EXPECTEDWEIGHT) VALUES
(#carrierSelectInput,
#pieceCountInput, #weightinput)")
{
SqlCommand generateApptNum = new SqlCommand();
View appNumView = new View();
insertData.Connection = sqlConnection1;
string carrierSelectInput = DropDownList1.Text;
string pieceCountInput = TextBox1.Text;
string weightInput = TextBox2.Text;
insertData.Parameters.Add("#carrierSelectInput",
carrierSelectInput.VarChar);
insertData.Parameters.Add("#pieceCountInput",
pieceCountInput.Int);
insertData.Parameters.Add("#weightInput",
weightInput.Int);
cmd.InsertCommand = insertData;
sqlConnection1.Open();
insertData.ExecuteNonQuery();
generateApptNum.ExecuteNonQuery();
sqlConnection1.Close();
}
}
}
}
}
EDIT: I have tried running the SQL into the DB and it gave an error, so I changed it(updated in code) but it puts in at ID=0...
I know you have already committed to your plan, but, I feel that I have to point out that, due to the sub select for the Max id value in your query, the insert statement has the potential to be much slower than a normal insert.
If you are planning on inserting a large number of rows or creating an API for use throughout the code I highly recommend either adjusting the column definition to be an identity column or to consider using a a sequence to generate the ids.
The issue could be that you need to specify the CommandType to be CommandType.Text on the insertData command. There is a lot going on in the original code with multiple sqlcommands being declared. I think the code could be simplified as such:
protected void ButtonClick(object sender, EventArgs e)
{
using (var sqlConnection1 = new SqlConnection("data source=testServer;initial catalog=testCat;integrated security=True;"))
using (var insertData = new SqlCommand("insert into tempExample (id, code, description) values ((select max(coalesce(id, 1)) from tempExample)+1, #code, #description)", sqlConnection1))
{
insertData.CommandType = CommandType.Text;
insertData.Parameters.AddWithValue("#code", "Testing4");
insertData.Parameters.AddWithValue("#description", "Testing3");
sqlConnection1.Open();
insertData.ExecuteNonQuery();
sqlConnection1.Close();
}
}
Update - I changed the code above to reflect a working test on my local machine. Note that the connection string format is different (lack of spaces).

Adding Data to Database but get a breakpoint everytime a function is called

I am trying to write myself a Music record database program.
It works perfectly untill I try using a form to add data using input from textboxes and a button.
It generates a break point and the following error
An Unhandled exception of type 'System.ArgumentException' Occured in
System.Data.dll
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace Musicrecord
{
public partial class Form3 : Form
{
public Form3()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
--> using(var connection = new SqlConnection("connectionString"))**
{
connection.Open();
var sql = "INSERT INTO Table(Artist, Album, Release Year) VALUES(#Artist, #Album, #Release year)";
using(var cmd = new SqlCommand(sql, connection))
{
cmd.Parameters.AddWithValue("#Artist", textBox1.Text);
cmd.Parameters.AddWithValue("#Album", textBox2.Text);
cmd.Parameters.AddWithValue("#Release Year ", textBox3.Text);
cmd.ExecuteNonQuery();
}
I haven't found after several hours of googling a solution.
If connectionString is a local variable, you need to use it as;
using(var connection = new SqlConnection(connectionString))
not
using(var connection = new SqlConnection("connectionString"))
If you use it as "connectionString", SqlConnection expects it is a valid connection string. But it is not.
Also, if your column name more than one word, you need to use it with square brackets like [Release Year]. It is the same as it's paramter name.
And don't use AddWithValue. It may generate unexpected results. Use .Add() method or it's overloads.
using(var connection = new SqlConnection(connectionString))
using(var cmd = connection.CreateCommand())
{
cmd.CommandText = "INSERT INTO Table(Artist, Album, [Release Year]) VALUES(#Artist, #Album, #ReleaseYear)";
cmd.Parameters.Add(#Artist, SqlDbType.NVarChar).Value = textBox1.Text;
cmd.Parameters.Add(#Album, SqlDbType.NVarChar).Value = textBox2.Text;
cmd.Parameters.Add(#ReleaseYear, SqlDbType.NVarChar).Value = textBox3.Text;
connection.Open();
cmd.ExecuteNonQuery();
}
I assumed your all data types are NVarChar. Also it is a good practice to specify size value as a third parameter in .Add() method.

C# connection issue

My first issue: I am trying to establish connection to MySql database, but I keep getting error when I debug it with Visual Studio:"Connection must be valid and open."
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Threading;
using MySql.Data.MySqlClient;
using MySql.Data.Types;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
MySqlConnection conn;
string myConnectionString;
myConnectionString = "server=localhost;User Id=root;database=test3";
using (conn = new MySqlConnection(myConnectionString))
{
DateTime startTime = DateTime.Now;
MySqlCommand cmd = new MySqlCommand("SELECT * FROM department");
// sleep for 2.5s
Thread.Sleep(2500);
conn.Open();
var reader = cmd.ExecuteReader();
conn.Close();
}
}
}
My second issue: if there a way to display all this on a ASP.NET Web form (I want to leave code on server side), but display data something like ListView or GridView? Thanks in advance
You need to call conn.Open() before using it.
You forgot to attach your connection to the command:
cmd.Connection = conn;

Multiple "Insert Into" operation under same event

Guys I searched around like hell but nothing could help me so I think it's time to ask. Before I write to problem, I need to say that I need it's solution asap because it's a project that I have to give tomorrow and I stuck on the same subject since ages and still losing time.
OK here it is;
I need to add a book to a library system, at first phase I add the standard book features which has only "one value" like (name, page number, publishing time, publisherID etc) but as wanted by me book MAY HAVE MULTIPLE WRITERS AND CATEGORIES which killed me and still I can't resolve. I tried to add book to it's (books) table then with the information i got from that i did an other insert op. to (bookWriters) table. While I check it, compiler does everything in order without error but when I check table from SQL Server there is nothing.
Here is what I tried to do;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Data.SqlClient;
namespace Project_
{
public partial class addBook: Form
{
public addBook()
{
InitializeComponent();
}
public main refForm;
int chosenWritersNumber; //how many writers have selected on listbox
int[] writers= { }; // an array list that i keep writerIDs that comes from class
int ind = 0;
int insertedBookID; // to catch latest added book's ID
int chosenWriterID; // writer that will be added
private void bookAddingPreps()
{
chosenWritersNumber = lstWriters.SelectedItems.Count;
Array.Resize<int>(ref writers, chosenWritersNumber );
for (int i = 0; i < chosenWritersNumber ; i++)
{
writers[i] = ((X_Writers)lstWriters.SelectedItems[i]).XWriterID;
}
}
private void addMainBookInfos()
{
SqlConnection con = new SqlConnection(Conn.Activated);
SqlCommand com = new SqlCommand("AddBook", con);
com.CommandType = CommandType.StoredProcedure;
com.Parameters.AddWithValue("#BookISBN", txtISBN.Text);
con.Close();
}
private void catchAddedBookID()
{
SqlConnection con = new SqlConnection(Conn.Activated);
SqlCommand com = new SqlCommand("catchBookID", con);
com.CommandType = CommandType.StoredProcedure;
con.Open();
SqlDataReader dr = com.ExecuteReader();
if (dr.HasRows)
{
while (dr.Read())
{
insertedBookID = dr.GetInt32(0);
}
}
dr.Close();
con.Close();
}
private void addWritersOfTheBook()
{
chosenWriterID = writers[ind];
SqlConnection con = new SqlConnection(Conn.Activated);
SqlCommand com = new SqlCommand("addBookWriters", con);
com.CommandType = CommandType.StoredProcedure;
com.Parameters.AddWithValue("#BookID", insertedBookID);
com.Parameters.AddWithValue("#WriterID", chosenWriterID);
con.Close();
}
I call these methods on click of a button. You see also stored procedure names but as I checked they all correct, there must be a mistake in this page that I still cant see but if it's needed I can add what procedures writes but they all tested and seems working.
So as i said, when i do this, as ind = 0, a writer should have been added, break point shows everything is ok and compiler doesnt show any errors but when I check sql server table, its empty.
Written in C# with using Visual Studio 2010 Ultimate and SQL Server 2008 Dev.
Thanks
You forget to execute your SqlCommand's. Make a call to command.ExecuteNonReader(); to execute it without expecting any results. see: http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.aspx
Apart form that, dont forget to dispose the resources acquired in your methods. Something like:
private void addMainBookInfos()
{
using (SqlConnection con = new SqlConnection(Conn.Activated))
using (SqlCommand com = new SqlCommand("AddBook", con))
{
com.CommandType = CommandType.StoredProcedure;
com.Parameters.AddWithValue("#BookISBN", txtISBN.Text);
com.ExecuteNonQuery()
// close can be omitted since you are already using the 'using' statement which automatically closes the connection
con.Close();
}
}

Categories