SQL System.NullReferenceException [duplicate] - c#

This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 8 years ago.
I wrote a c# function to populate a ext.net store. It works fine in one application, but the same code does not work in another. I am getting a System.NullReferenceException on line 26. This is line 26:
MyConnection.ConnectionString = ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;
Here is my c# function:
protected void fillStore(Ext.Net.Store store, string query)
{
SqlDataReader MyReader;
SqlConnection MyConnection = new SqlConnection();
MyConnection.ConnectionString = ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;
SqlCommand fillCommand = new SqlCommand();
fillCommand.CommandText = "select id, name from b2b_group";
fillCommand.CommandType = CommandType.Text;
fillCommand.Connection = MyConnection;
fillCommand.Connection.Open();
MyReader = fillCommand.ExecuteReader(CommandBehavior.CloseConnection);
store.DataSource = MyReader;
store.DataBind();
fillCommand.Dispose();
MyConnection.Dispose();
}
For simplification, I replaces the query string that would be passed through by a hard-coded one of "select id, name from b2b_group".
I can not seem to figure out why it is giving a nullReferenceException, especially seeing as I have the same code working in another project.
I know that there is some little thing I am overseeing, could anyone spot it?
Thank you so much!

The connection string 'MyConnectionString' is not present in your configuration file. Check connectionStrings section.

Related

Retrieving image from SQL Server to ASP.NET imagebutton [duplicate]

This question already has answers here:
Creating a byte array from a stream
(18 answers)
Closed 2 years ago.
I am trying to insert data from ASP.NET into SQL Server and retrieve it from SQL Server back to ASP.NET.
The insert part is done, but I am having problems to retrieve data. I am using this code, but is throwing an error:
SqlConnection con = new SqlConnection(myconnstrng);
con.Open();
SqlCommand cmd = new SqlCommand("selection", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#id", parameter);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet dsa = new DataSet();
da.Fill(dsa);
if (dsa.Tables[0].Rows.Count > 0)
{
MemoryStream ms = new MemoryStream((byte[])dsa.Tables[0].Rows[0]["Data"]);
string strBase64 = Convert.ToBase64String(ms);
ImageButton2.ImageUrl = "data:Image/png;base64," + strBase64;
}
and the error I got is :
Cannot convert from 'System.IO.MemoryStream' to 'byte[]'
I am new to programming, and if someone could help me about this problem.
Thanks to everyone !
The particular line you are stuck on, you don't need a MemoryStream at all. You can pass the value from the DataTable straight to ToBase64String.
But you can save yourself some bother with these tips:
ALWAYS dispose the connection, command and adapter/reader correctly, by putting them in using blocks`
For a single result, you can skip the table and adapter, and just use (byte[]) cmd.ExecuteScalar().
If you have more than one row which you need to process (as opposed to just displaying in a grid view), you may find it again easier to skip the DataTable and grab data out via this:
using(var reader = cmd.ExecuteReader())
{
while(reader.Read())
DoSomethingWithResult(reader.IsDBNull(0) ? null : reader.GetBytes(0));
}
Generally, DoSomethingWithResult should not be very heavy processing, or you will block the SQL server. If so, store in memory and process it afterwards.

Must declare the scalar variable "#GenName" [duplicate]

This question already has answers here:
Error on sql database "Must declare the scalar variable"
(2 answers)
Closed 4 years ago.
I am getting this error when trying to run the code below. Any insight on to what I am doing wrong? I am pretty new to this, and want to get this to work pretty bad. I have gotten zero help from this site so far in a previous question I asked. But decided to give this forum another shot, before giving up on stackoverflow
protected void SaveButton_Click(object sender, EventArgs e)
{
SqlConnection myConnection =
new SqlConnection(#"Data Source=.\sqlexpress;Initial Catalog=TESTdatabase;Integrated Security=True");
SqlCommand myCommand = new SqlCommand(
"INSERT into tblGenerator (GeneratorName, GeneratorAddress, GeneratorCity, GeneratorState, GeneratorZip, GeneratorPhone, GeneratorContact, GeneratorEPAID)" +
"VALUES (#GenName, #GenAdd, #GenCity, #GenState, #GenZip, #GenPhone, #GenContact, #GenEPAID), myConnection");
myCommand.Parameters.AddWithValue("#GeneratorName", GenName.Text);
myCommand.Parameters.AddWithValue("#GeneratorAddress", GenAdd.Text);
myCommand.Parameters.AddWithValue("#GeneratorCity", GenCity.Text);
myCommand.Parameters.AddWithValue("#GeneratorState", GenState.Text);
myCommand.Parameters.AddWithValue("#GeneratorZip", GenZip.Text);
myCommand.Parameters.AddWithValue("#GeneratorPhone", GenPhone.Text);
myCommand.Parameters.AddWithValue("#GeneratorContact", GenContact.Text);
myCommand.Parameters.AddWithValue("#GeneratorEPAID", GenEPAID.Text);
myConnection.Open();
myCommand.Connection = myConnection;
myCommand.ExecuteNonQuery();
myConnection.Close();
}
First, Stackoverflow is very helpful :) Don't give up on this platform.
Now for your question:
The parameters your SQL statement is expecting are:
(#GenName, #GenAdd, #GenCity, #GenState, #GenZip, #GenPhone, #GenContact, #GenEPAID)
While you later assign them with different names.
It should be:
myCommand.Parameters.AddWithValue("#GenName", GenName.Text);
myCommand.Parameters.AddWithValue("#GenAdd", GenAdd.Text);
myCommand.Parameters.AddWithValue("#GenCity", GenCity.Text);
myCommand.Parameters.AddWithValue("#GenState", GenState.Text);
myCommand.Parameters.AddWithValue("#GenZip", GenZip.Text);
myCommand.Parameters.AddWithValue("#GenPhone", GenPhone.Text);
myCommand.Parameters.AddWithValue("#GenContact", GenContact.Text);
myCommand.Parameters.AddWithValue("#GenEPAID", GenEPAID.Text);
When using #parameter , you must assign a value to a parameter with the same exact name.

Do parameterized queries work with MySQL in c#? [duplicate]

This question already has answers here:
Parameterized Query for MySQL with C#
(6 answers)
Closed 4 years ago.
I am attempting to run a query using a parameter in C#. I am getting an issue where no rows are being returned. I am pulling the sql from a file and putting it into the command text. When the query (a SELECT statement) is run, no results are returned. I have confirmed that the result is in my database and that the query is correct (after replacing the param) by running it normally.
conn.Open();
//create the command
var command = conn.CreateCommand();
//Read sql from file
FileInfo file = new FileInfo("SQL/GetPage.sql");
string script = file.OpenText().ReadToEnd();
command.CommandText = script;
command.Parameters.AddWithValue("?PageID", PageName);
command.Prepare();
MySqlDataReader rdr = command.ExecuteReader();
rdr.Read();
SQL:
SELECT * FROM `Page` WHERE PageID = '?PageID'
I have tried with both the prepare and without it. I have no clue why it is not working. Also, I am only expecting one result max (PageID is unique), so that is why it isn't in a loop. I also know my connection is good because I hardcoded the query without the where clause and it worked fine.
Please let me know if anyone has any suggestions.
Thanks
Read() just advances the DataReader to the next record (this is why it used in a loop). You need to extract the data from this record
while (rdr.Read())
{
int i = rdr.GetInt32(0);
string s = rdr.GetString(1);
}

Fields not inserting into my SQL Server [duplicate]

This question already has answers here:
SqlCommand INSERT INTO query does not execute
(3 answers)
Closed 7 years ago.
I am using visual studio, i have a connection to an SQL server and im trying to update a table in the database.
I am not recieving any errors nor am i updating anything
Below is the code i have used
protected void Btn1_Click(object sender, EventArgs e)
{
//SQL for insert here.
string MyConnectionString = ConfigurationManager.ConnectionStrings
["testconnect"].ConnectionString;
SqlConnection myConnection = new SqlConnection();
myConnection.ConnectionString = MyConnectionString;
myConnection.Open();
SqlCommand cmd = new SqlCommand("insert into Don_Test (ID, Test) values ('" + IDTxt.Text + "','" + TESTTxt.Text + "')", myConnection);
//Call refresh
refreshPage();
myConnection.Close();
}
Actually, you are not executing your query, but just opening connection and closing it later.
Add line of code cmd.ExecuteNonQuery(); before refreshPage().
Also notice - concatenating query text is very bad idea since it leads to SQL injection attack.
Use parameterized query instead.

Cant identify the issue in the mysql request

I have two functions and one is working perfectly and the other is not, the code is the same apart from that the non functioning code has a WHERE in the database request, I just cant get it to work and I am desperate. The cID is a string given to the function and thats the ONLY thing that is correct at the moment
Geotag c = new Geotag();
String myConnection = WebConfigurationManager.ConnectionStrings["mydatabase"].ConnectionString;
MySqlConnection myConn = new MySqlConnection(myConnection);
String strSQL = "SELECT Id,geotag,item,date,nameofplace FROM geolist WHERE Id = 'cID';";
MySqlCommand myCommand = new MySqlCommand();
myCommand.Connection = myConn;
myCommand.CommandText = strSQL;
try
{
myConn.Open();
MySqlDataReader myReader;
myReader = myCommand.ExecuteReader();
myReader.Read();
while (myReader.Read())
{
my reader is empty so it skips and moves on....why? i tried what i belive is everything, like without ' ' around the cID string.
If I remove the WHERE = cID I will directly be given an object back that is the first in the list so I know the code works. The database has the matched string and even if I hard code the string into the WHERE it still wont work so its something else I am missing here.
You are comparing an Id field, so you'll have probably one record back but you are calling the Read method twice
myReader.Read();
while (myReader.Read()) // <--- empty

Categories

Resources