ExecuteScalar: Connection property has not been initialized. SQL Server Connection - c#

I wrote this code to read the images stored in SQL Server database however I got this error:
ExecuteScalar: Connection property has not been initialized.
Since I already initialized the connection, I am not sure what the problem is.
SqlConnection myConnection = null;
try
{
myConnection = new SqlConnection("Data Source=Source; Initial Catalog=Database; user ID=Test; Password=Test");
SqlCommand myCommand = new SqlCommand ("SELECT imagedata FROM Database , myConnection");
myConnection.Open();
// Get the image from the database.
byte[] imagedata = (byte[])myCommand.ExecuteScalar();
if (imagedata != null)
{
return image;
}
else
{
return null;
}
}
finally
{
myConnection.Close();
}

You have put both your Select statement and your connection in double quotes ("). i.e you didn't specify the SqlCommand's Connection property actually. Change your SqlCommand from this:
SqlCommand myCommand = new SqlCommand ("SELECT imagedata FROM Database , myConnection");
To this:
SqlCommand myCommand = new SqlCommand ("SELECT imagedata FROM Database" , myConnection);
Or like this:
SqlCommand myCommand = new SqlCommand("SELECT imagedata FROM Database");
myCommand.Connection = myConnection;

Related

Data not appearing in SQL Database

I'm trying to INSERT data into my SQL database but its not showing anything at all.
This is a for an online role-playing game . There is no error but when I refresh my browser for phpmyadmin using XAMP, no data is being shown.
MySqlConnection connection = new MySqlConnection(connectionString);
connection.Open();
string checkDatabase = "select * from players where username = #playerName";
MySqlCommand command = new MySqlCommand(checkDatabase, connection);
command.Parameters.AddWithValue("#playerName", player.SocialClubName);
MySqlDataReader reader = command.ExecuteReader();
if(reader.Read())
{
player.SendChatMessage("There is an account with the assiociated Social Club Profile!");
}
else
{
MySqlConnection connection1 = new MySqlConnection(connectionString);
connection1.Open();
string playerInsert = "insert into players(username,password) VALUES (#user,#password)";
MySqlCommand command1 = new MySqlCommand(playerInsert, connection1);
command1.Parameters.AddWithValue("#user", player.SocialClubName);
command1.Parameters.AddWithValue("#password", password);
connection1.Close();
}
connection.Close();
You need to execute the query. Try:
...
command1.ExecuteNonQuery();
That's cause you are not executing the query at all as can be seen in below posted code
string playerInsert = "insert into players(username,password) VALUES (#user,#password)";
MySqlCommand command1 = new MySqlCommand(playerInsert, connection1);
command1.Parameters.AddWithValue("#user", player.SocialClubName);
command1.Parameters.AddWithValue("#password", password);
command1.ExecuteNonQuery(); //execute the query
connection1.Close();

can't read int value from sql database

I have tried this code in C#, and it's not working - I can't get an input id, every time I run it, the value of id is 0.
SqlConnection con = new SqlConnection("Data Source=.;Initial Catalog=sms;Persist Security Info=True;User ID=boy;Password=coco");
int id;
con.Open();
string sql = "select * from Staff_Management where Emp_Name = '"+sName+"'; ";
SqlCommand cmd = new SqlCommand(sql, con);
SqlDataReader read = cmd.ExecuteReader();
if (read.Read())
{
id = read.GetInt32(0);
TM_AC_SelectId.Text = id.ToString();
}
else
{
MessageBox.Show("Error 009 ");
}
con.Close();
You should try to follow the accepted best practices for ADO.NET programming:
use parameters for your query - always - no exceptions
use the using(...) { .... } construct to ensure proper and quick disposal of your resources
select really only those columns that you need - don't just use SELECT * out of lazyness - specify your columns that you really need!
Change your code to this:
// define connection string (typically loaded from config) and query as strings
string connString = "Data Source=.;Initial Catalog=sms;Persist Security Info=True;User ID=boy;Password=coco";
string query = "SELECT id FROM dbo.Staff_Management WHERE Emp_Name = #EmpName;";
// define SQL connection and command in "using" blocks
using (SqlConnection con = new SqlConnection(connString))
using (SqlCommand cmd = new SqlCommand(query, con))
{
// set the parameter value
cmd.Parameter.Add("#EmpName", SqlDbType.VarChar, 100).Value = sName;
// open connection, execute scalar, close connection
con.Open();
object result = cmd.ExecuteScalar();
con.Close();
int id;
if(result != null)
{
if (int.TryParse(result.ToString(), out id)
{
// do whatever when the "id" is properly found
}
}
}

Populate listview with data received from SQL query

I am currently trying to populate a listview with some data I have pulled from my database table; but not sure where to start; I have tried the following:
lstData.DataSource = conn;
lstData.DataBind();
But that causes an error:
"Data source is an invalid type. It must be either an IListSource,
IEnumerable, or IDataSource. MVC"
Am I using the correct query strings in order to populate my listview?
Thanks,
Callum
C# Code:
string ssConnectionString = "Server connection";
SqlConnection conn = new SqlConnection(ssConnectionString);
conn.Open();
SqlCommand command = conn.CreateCommand();
command.CommandText = "SELECT Category FROM [dbo].[Category] WHERE CategoryID = '16'";
command.ExecuteNonQuery();
string com = command.ExecuteScalar().ToString();
lblSQL.Text = com;
conn.Close();
Using your code as a base to start from you may want to try the following: I assume your connection in "Server connection" is a place holder for a real connection string and you know what should go there.
string ssConnectionString = "Server connection";
SqlConnection conn = new SqlConnection(ssConnectionString);
conn.Open();
SqlCommand command = conn.CreateCommand();
command.CommandText = "SELECT Category FROM [dbo].[Category] WHERE CategoryID = '16'";
SqlDataAdapter da = new SqlDataAdapter(command);
DataTable dataTable;
da.Fill(dataTable);
lstData.DataSource = dataTable;
lstData.DataBind();
conn.Close();

Error binding in GetColumnNumber at row 1

I got this OfficeWriter error when debugging the console application. I used methods to retrieve config details for the database used in the coding from the master database, and ended up having this error.
Error binding in GetColumnNumber at row 1
Attached here is partial coding for my work. Anyone can explain me what the error is?
SqlDataReader rdSource = getSource();
SqlDataReader rdDestination = getDestination();
SqlDataReader rdCode = getCode();
while (rdSource.Read() && rdDestination.Read())
{
string src = rdSource["Value"].ToString();
string dest = rdDest["Value"].ToString();
ExcelTemplate XLT = new ExcelTemplate();
XLT.Open(src);
DataBindingProperties dataProps = XLT.CreateBindingProperties();
XLT.BindData(rdCode, "Code", dataProps);
XLT.Process();
XLT.Save(dest);
}
//rdCode method
SqlDataReader rdConnection = getConnection(); //method for getting connection from master
while (rdConnection.Read())
{
string con = rdConnection["Value"].ToString();
SqlConnection sqlCon = new SqlConnection(con);
string SQL = "SELECT * FROM Sales.Currency";
sqlCon.Open();
SqlCommand cmd = new SqlCommand(SQL, sqlCon);
cmd.ExecuteReader();
sqlCon.Close();
}
return rdConnection;
//getConnection method
string strCon = ConfigurationManager.ConnectionStrings["Master"].ConnectionString;
SqlConnection sqlCon = new SqlConnection(strCon);
string cSQL = "SELECT Value FROM dbo.COMMON_CONFIG WHERE Value = 'Data Source=localhost;Initial Catalog=Test;Integrated Security=True'";
SqlCommand cmd = new SqlCommand(cSQL, sqlCon);
sqlCon.Open();
return new SqlCommand(cSQL, sqlCon).ExecuteReader(CommandBehavior.ConnectionString);
//getSource & getDestination methods
string strCon = ConfigurationManager.ConnectionStrings["Master"].ConnectionString;
SqlConnection sqlCon = new SqlConnection(strCon);
string srcPath = #"FILE PATH NAME"; //change to destPath for getDestination
string sSQL = "SELECT Value FROM dbo.COMMON_CONFIG WHERE Value = '" + srcPath + "'";
SqlCommand cmd = new SqlCommand(cSQL, sqlCon);
sqlCon.Open();
return new SqlCommand(cSQL, sqlCon).ExecuteReader(CommandBehavior.ConnectionString);
The error is a generic message that is thrown by ExcelWriter when it is unable to bind data to the template.
I think this might be caused by your getCode() method. In getCode(), you use a SQLDataReader to retrieve the connection string for the database:
SqlDataReader rdConnection = getConnection(); //method for getting connection from master
Then you execute a SQL query against that database, but you don't actually get a handle on the SqlDataReader that is executing the SQL query to return the data.
SqlCommand cmd = new SqlCommand(SQL, sqlCon);
cmd.ExecuteReader(); //Note: This returns the SqlDataReader that contains the data
Then you return rdConnection, which is the SQLDataReader for the connection string - not the data you are trying to import. rdConnection contained 1 row and you already called Read(), so there are no records left to read.
SqlDataReader rdCode = getCode();
...
XLT.BindData(rdCode, "Code", dataProps);
The SQL reader you are binding is the used 'connection string', rather than your sales data. I would recommend the following:
Return the new SqlDataReader that is generated by cmd.ExecuteReader() in getCode(), rather than rdConnection.
Do not close the connection to this new SqlDataReader. ExcelWriter needs to be able to read the data reader in order to bind the data. If you close the connection, ExcelWriter will not be able to bind data correctly.

Retrieving an image from SQL Server

I wrote this code but faced an exception that said: Parameter Not Valid.
string connstr = #"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\db.mdf;Integrated Security=True;User Instance=True";
SqlConnection conn = new SqlConnection();
conn.ConnectionString = connstr;
conn.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandText = "SELECT * FROM tbl";
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd;
DataTable dt = new DataTable();
da.Fill(dt);
byte[] barrImg = (byte[])dt.Rows[1]["image"];
MemoryStream mstream = new MemoryStream();
mstream.Write(barrImg, 0, barrImg.Length);
mstream.Seek(0, SeekOrigin.Begin);
img.Image = Image.FromStream(mstream);
mstream.Close();
The exception is:
Parameter is not valid.
in the Image.FromStream line of code.
I checked the value that in datatable was assigned to the image field. It was System.Byte[]. I traced the code. Every thing seems to be correct. But it does not work.
I searched around this problem. Another site preferred to set mstream.Position = 0. But that does not work.
I stored my image by this code.If it maybe that I saved this wrong!
string connstr = #"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\db.mdf;Integrated Security=True;User Instance=True";
SqlConnection conn = new SqlConnection();
conn.ConnectionString = connstr;
conn.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
string sql = "INSERT INTO tbl (name, family, image) VALUES ('name', 'family', '{0}')";
sql = string.Format(sql, Image.FromFile("test.jpg"));
cmd.CommandText = sql;
cmd.ExecuteNonQuery();
conn.Close();
new code to save the image:
public byte[] ReadFile(string sPath)
{
byte[] data = null;
FileInfo fInfo = new FileInfo(sPath);
long numBytes = fInfo.Length;
FileStream fStream = new FileStream(sPath, FileMode.Open, FileAccess.Read);
BinaryReader br = new BinaryReader(fStream);
data = br.ReadBytes((int)numBytes);
return data;
}
and :
private void cmdSave_Click(object sender, EventArgs e)
{
string connstr = #"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\db.mdf;Integrated Security=True;User Instance=True";
byte[] imageData = ReadFile("test.jpg");
SqlConnection CN = new SqlConnection(connstr);
string qry = "insert into tbl (name, family, image) VALUES ('name', 'family', '{0}')";
qry = string.Format(qry, imageData);
SqlCommand SqlCom = new SqlCommand(qry, CN);
CN.Open();
SqlCom.ExecuteNonQuery();
CN.Close();
}
Um, that's not going to work.
Your code that "stores" the image, well, doesn't really do what you think it does.
It is putting the value "test.jpg" into the image field. That isn't the binary image data; only the filename.
So, when you go to pull it back out the Image.FromStream(mstream) call is going to blow chunks because the value "test.jpg" is not an image.. ergo: the parameter is not valid
Here is an example of what you need to be doing to actually put the image into the database:
http://www.codeproject.com/Articles/21208/Store-or-Save-images-in-SQL-Server
You close the stream then try to pull an image from the stream, hence the error "cannot access a closed stream."
Try swapping the order of your last two lines:
img.Image = Image.FromStream(mstream);
mstream.Close();
using (MemoryStream mstream = new MemoryStream((byte[])dt.Rows[1]["image"]))
{
img.Image = Image.FromStream(mstream);
}
Would simplify things. I suspect your problem would be you need to call mStream.Flush() after write and before the seek.
To put an image in to a database, one way is.
string connstr = #"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\db.mdf;Integrated Security=True;User Instance=True";
using(SqlConnection conn = new SqlConnection(connstr))
{
using (SqlCommand comm = new SqlCommand(conn))
{
comm.CommandText = "INSERT INTO tbl (name, family, image) VALUES (#name,#family,#Content)";
comm.Parameters.Add(new SqlParameter("name",DbType.String,"Fred"));
comm.Parameters.Add(new SqlParameter("family",DbType.String,"Flintstone"));
using(FileStream fs = new FileStream("FredWilmaBamBamAndDino.jpg",FileMode.Open,FileAccess.Read))
{
comm.Parameters.Add(new SqlParameter("content",DbType.Image,fs));
}
cmd.ExecuteNonQuery();
}
}
Notice it puts the content of teh file in the database. Since in the case of a jpg that content is most definitely not a string, use a parameterised query. Which youi should be doing anyway, develop a good habit.
You also need to suss out using, your code was leaking resources all over the place.

Categories