I have stored an image in SQL Server. First I have converted the image into bytes and I have saved it in SQL Server and very much done with saving.....when I try to invoke the respective image's bytes value from SQL Server which I saved and when I try to implement that in C#, I am getting a error like
NullReferenceException was unhandled by user code
Object Reference not set to an instance of an object
Here is my code:
protected void GetImageButton_OnClick(object sender, EventArgs e)
{
SqlConnection connection = new SqlConnection();
connection.ConnectionString = #"";
connection.Open();
SqlCommand command = new SqlCommand();
command.Connection = connection;
command.CommandType = CommandType.StoredProcedure;
command.CommandText = "uspgetimage";
command.Parameters.AddWithValue("#imageID", getimagebutton.Text);
DataSet dataset = new DataSet();
SqlDataAdapter adapter = new SqlDataAdapter();
adapter.SelectCommand = command;
adapter.Fill(dataset);
Byte[] bytes = command.ExecuteScalar() as byte[];
string base64String = Convert.ToBase64String(bytes, 0, bytes.Length);
Image.ImageUrl = "data:image/jpeg;base64," + base64String;
}
Kindly have a look on it and help me to get out from this friends.
Before NullReferanceException, I don't believe this lines don't throw any exception..
SqlConnection connection = new SqlConnection();
connection.ConnectionString = #"";
connection.Open();
You can't open a connection before you initialize SqlConnection.ConnectionString property. In your case, your connection string is an empty string. How do you expect this connection connect to your sql server?
My suggestion is, read a book about C# and using it with databases like Begining C# 5.0 Databases
For NullReferanceException, I already mentioned in my comment what you should do.
It's likely that you're getting a NullReferenceException from your call to ExecuteScalar. From the documentation:
Return Value
The first column of the first row in the result set, or a null reference ... if the result set is empty.
Emphasis mine.
And for what it's worth, SqlConnection, SqlCommand, DataSet and SqlDataAdapter are all IDisposable. You should call Dispose on them, although the value of disposing DataSet is arguable.
Try running the stored procedure in SQL Server to see if it returns any value using
EXEC uspgetimage 'COmma seperated Parameter List'
Related
I'm trying to update a CLOB column in my database with a long string containing the HTML contents of an email. There are 18,000 characters in the record I'm having an issue with.
The below code will work if I set the html variable to "short string". But if I try to run the code with the long 18,000 character HTML string, I get this error: "Oracle.DataAccess.Client.OracleException ORA-22922: nonexistent LOB value ORA-02063: preceding line from ((servername))"
public static void UpdateHtmlClob(string html, string taxId,string un, string pw)
{
using (OracleConnection conn = new OracleConnection())
{
try
{
conn.ConnectionString = "User Id=" + un + ";Password=" + pw + ";Data Source=server.com;";
conn.Open();
OracleCommand cmd = new OracleCommand();
string indata = html;
cmd.CommandText = "UPDATE table1 SET HTML_BODY = :clobparam";
OracleParameter clobparam = new OracleParameter("clobparam", OracleDbType.Clob, indata.Length);
clobparam.Direction = ParameterDirection.Input;
clobparam.Value = indata;
cmd.Parameters.Add(clobparam);
cmd.Connection = conn;
cmd.ExecuteNonQuery();
conn.Close();
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
conn.Close();
}
}
}
Before you edited your code to reflect my answer, there were two problems with your code that I saw.
Firstly, you need to use a colon in your command text to tell Oracle that clobparam is a bind variable, not a column name:
cmd.CommandText = "UPDATE table1 SET HTML_BODY = :clobparam";
Secondly, you were not setting the database connection anywhere on the command. Which connection should the command be using? In your situation you have only one connection but more generally it may be possible to have more than one connection open. Add the line
cmd.Connection = connection;
or alternatively create the command using
OracleCommand cmd = connection.CreateCommand();
Of course, it would be nice if Oracle.DataAccess returned an error message that gave you the slightest hint that this was what you were doing wrong.
Anyway, now that you've edited your question to include the critical detail ORA-02063: preceding line from ((servername)), which tells us that you are using a database link, all I can really do is echo what I wrote in the comment: connect direct to the remote database to transfer LOB data, don't use a database link.
The code below has been used successfully in other parts of the application without fault.
However, for some reason, an InvalidOperationException is thrown when it comes time to read data from the Access database.
The code below contains only the essentials (not the items that are trying to be read, as that would made readability difficult).
Why am I getting this error, despite the fact I am calling the "Open" method on my connection?
Code follows:
string connString = "Provider= Microsoft.ACE.OLEDB.12.0;" + "Data Source= C:\\temp\\IntelliMed.accdb";
string queryString = "SELECT patientID, firstName, lastName, patientGender, dateOfBirth, residentialAddress, postalAddress, nationalHealthNumber, telephoneNumber, cellphoneNumber, cscNumber FROM PatientRecord WHERE patientID = #patientID";
try
{
using (OleDbConnection con = new OleDbConnection(connString))
{
con.Open();
OleDbCommand command = new OleDbCommand();
command.CommandText = queryString;
command.Parameters.AddWithValue("#patientID", patientID);
command.Connection = ctnPatientRecord;
OleDbDataReader prescriptionDetailsReader = command.ExecuteReader();
while (prescriptionDetailsReader.Read())
{
//Read stuff.
}
//Close the reader.
}
//Close the connection.
} //Method "closing" bracket.
Any help is gratefully received. Thanks in advance.
I think you should associate the command with the connection
command.Connection = con;
or better yet create the command through the connection using the CreateCommand method instead of the constructor.
I have seen lots of answers to connect to MS Access via OleDB but there is not good answer for SQL Server. I try to connect to a SQL Server database via OleDB provider in my C# program.
This is the connection string I am providing.
Provider=SQLOLEDB;Data Source=<servername>;Initial Catalog=<dbname>;Integrated Security=SSPI
But it gives me error
‘Keyword not support ‘Provider’’
What I want to do here is connect database via OleDB in C# program.
This works as expected on my side. From the error message I strongly suspect that you are using the SqlConnection class instead of the OleDbConnection (Of course you need to use all the other classes provided by OleDb like OleDbCommand, OleDbDataReader etc...)
string connStr = "Provider=SQLOLEDB;Data Source=<servername>;Initial Catalog=<dbname>;Integrated Security=SSPI";
using(OleDbConnection cnn = new OleDbConnection(connStr))
{
....
}
When in doubt, use the string builder in visual studio. That way unsupported keywords can't creep into your connection strings, the following is a wonderful example on how to use it.
http://www.c-sharpcorner.com/uploadfile/suthish_nair/how-to-generate-or-find-connection-string-from-visual-studio/
The same Connection string is working fine at my end.
I am posting my sample code which is executes successfully at my end
public string connStr = "Provider=SQLOLEDB;Data Source=.;Initial Catalog=<dbName>;Integrated Security=SSPI";
public OleDbConnection con;
protected void Page_Load(object sender, EventArgs e)
{
Test();
}
public void Test()
{
con = new OleDbConnection(connStr);
con.Open();
OleDbCommand cmd = new OleDbCommand("select * from tblApartments", con);
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
con.Close();
}
Please place breakpoint and check line to line and when your breakpoint comes to con.close(); then check ds, you can see the output.
The connection string you're using, considering the OLE DB provider, is correct. I didn't find any error in the connection string used, if you want to connect to a SQL Server data source.
Most probably, the reason of that error should be that you're not using correctly all the classes and objects required by the OLE DB provider, like OleDbCommand (that is similar to a SqlCommand but it's different), OleDbConnection, OleDbDataAdapter and so on. In a nutshell, the reason of that error should be this:
string connStr = "Provider=SQLOLEDB;Data Source=<servername>;Initial Catalog=<dbname>;Integrated Security=SSPI";
using(SqlConnection scn = new SqlConnection(connStr))
{
....
}
Indeed, using a SqlConnection object, the ConnectionString property doesn't support the keyword Provider and, executing your application, you got an error about a keyword not supported.
Have a look at this simple tutorial about the use of OLE DB provider.
I am trying to access an Access 2003 database remotely from my ASP.NET application. My code is:
DataSet dsImportedData = new DataSet();
System.Data.OleDb.OleDbConnection conn = new System.Data.OleDb.OleDbConnection();
conn.ConnectionString = #"Provider=MS Remote;Remote Provider=Microsoft.Jet.OLEDB.4.0;Remote Server=http://myIp;Data source=C:\myDatabase.mdb;";
try
{
System.Data.OleDb.OleDbCommand command = conn.CreateCommand();
command.CommandText = "SELECT * FROM myTable";
conn.Open();
System.Data.OleDb.OleDbDataAdapter adapter = new System.Data.OleDb.OleDbDataAdapter(command);
adapter.Fill(dsImportedData);
}
catch (Exception ex)
{
}
finally
{
conn.Close();
}
However, I am always getting an exception stating: {"[Microsoft][ODBC Microsoft Access Driver] Invalid SQL statement; expected 'DELETE', 'INSERT', 'PROCEDURE', 'SELECT', or 'UPDATE'."}
My command is basic, I have no idea what could be wrong with it. Did anyone confront with the same issue? Thanks!
Try this ....
String command = "SELECT * FROM myTable";
conn.Open();
System.Data.OleDb.OleDbDataAdapter adapter = new System.Data.OleDb.OleDbDataAdapter(command, conn);
adapter.Fill(dsImportedData);
Apparently the error can be caused by the specified table not existing. Just a thought...
Another thought would be to remove the remoting complexity and try to get to the most simple working code, possibly with a new access database just to start to narrow down what is causing the problem.
If you set the command type to Stores procedure it works for me.
command.CommandType = System.Data.CommandType.StoredProcedure;
Does anyone know how can I central the db connection in c# .net (perhaps in the mian.master)?
I have the following code for the db connection and used to call to the difference stored proc to retrieved data.
string strConnString = ConfigurationManager.ConnectionStrings["testString"].ConnectionString;
SqlConnection mySqlConnection = new SqlConnection(strConnString);
SqlCommand mySqlCommand = mySqlConnection.CreateCommand();
mySqlCommand.CommandText = "EXEC app_campaign_select #CampaignID=" + Request.QueryString["ixCampaign"].ToString();
mySqlConnection.Open();
SqlDataReader mySqlDataReader = mySqlCommand.ExecuteReader();
Instead of coding it in every pages and connection to the db multiple times, any way I can code the following connection code in the master page and only connecting to the db once, then each page can call it when need to be connect into the db
string strConnString = ConfigurationManager.ConnectionStrings["testString"].ConnectionString;
SqlConnection mySqlConnection = new SqlConnection(strConnString);
SqlCommand mySqlCommand = mySqlConnection.CreateCommand();
SqlDataReader mySqlDataReader;
Add it to a static DAL class and add parameters as needed.
public static void YourFunction() {
// your code
}
Note:
Beware this line: mySqlCommand.CommandText = "EXEC app_campaign_select #CampaignID=" + Request.QueryString["ixCampaign"].ToString();
If that QueryString comes from a user entered value somewhere, you could be open to SQL Injection.
Sure. Just create a helper class that has a few static methods in them for each type of return type you could have. Pass to one a string for stored procedure name and have an overloaded one that takes a string for a sql statment that you would pass in. You can also have one that just returns back a scalar value as well. So you would probably have 3 or so static methods you could call from any page.