Updating Database - c#

So Visual Studio tells me that my quotes are not right in the update statement. I feel it might be something more than that. I feel I am close but I don't see where I am going wrong in this sql statement. The point of the webpage is to update the database that is all for this step. Can someone help me out.
Here is my code.
P.S. - I did an insert statement similar to this but the string idString part all the way to the softwareReportRecord.Close(); was beneath the update statement and it worked.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
reportDateText.Text = DateTime.Today.ToShortDateString();
//code page 429
if (Page.IsPostBack)
{
Page.Validate();
if (Page.IsValid)
{
bugReportForm.Visible = false;
regMessage.Visible = true;
string typeOS = oSListbox.SelectedValue;
string reportDate = reportDateText.Text;
string hardware = hardwareText.Text;
string occurrence = occurrenceRadioButtonList.SelectedValue;
string shortDescription = shortDescriptionText.Text;
string longDescription = longDescriptionText.Text;
string actionsTaken = actionsTakenText.Text;
SqlConnection dbConnection = new SqlConnection("Data Source=.\\SQLEXPRESS;Integrated Security=true");
try
{
dbConnection.Open();
dbConnection.ChangeDatabase("BugsReport");
}
catch (SqlException exception)
{
if (exception.Number == 911)
{
SqlCommand sqlCommand = new SqlCommand("CREATE DATABASE BugsReport", dbConnection);
sqlCommand.ExecuteNonQuery();
regMessage.Text = "<p>Successfully created the database.</p>";
dbConnection.ChangeDatabase("BugsReport");
}
else
Response.Write("<p>Error code " + exception.Number
+ ": " + exception.Message + "</p>");
}
finally
{
regMessage.Text += "<p>Successfully selected the database.</p>";
}
try
{
string SQLString = "SELECT * FROM softwareLog";
SqlCommand checkIDTable = new SqlCommand(SQLString, dbConnection);
SqlDataReader idRecords = checkIDTable.ExecuteReader();
idRecords.Close();
}
catch (SqlException exception)
{
if (exception.Number == 208)
{
SqlCommand sqlCommand = new SqlCommand("CREATE TABLE softwareLog (reportID SMALLINT IDENTITY(100,1) PRIMARY KEY, typeOS VARCHAR(25), reportDate DATE, hardware VARCHAR(50), occurrence VARCHAR(15), shortDescription VARCHAR(100), longDescription VARCHAR(500), actionsTaken VARCHAR(25))", dbConnection);
sqlCommand.ExecuteNonQuery();
regMessage.Text += "<p>Successfully created the table.</p>";
}
else
regMessage.Text += "<p>Error code " + exception.Number
+ ": " + exception.Message + "</p>";
}
finally
{
string idString = "SELECT IDENT_CURRENT('softwareLog') AS reportID";
SqlCommand newID = new SqlCommand(idString, dbConnection);
SqlDataReader softwareReportRecord = newID.ExecuteReader();
softwareReportRecord.Read();
string reportID = Convert.ToString(softwareReportRecord["reportID"]);
softwareReportRecord.Close();
string editRecord = "UPDATE softwareLog SET "
+ "typeOS='" + typeOS + "', "
+ "reportDate='" + reportDate + "', "
+ "hardware='" + hardware + "' "
+ "occurrence='" + occurrence + "' "
+ "shortDescription='" + shortDescription + "' "
+ "longDescription='" + longDescription + "' "
+ "actionsTaken='" + actionsTaken + "' "
+ "WHERE reportID=" + reportID + ";";
SqlCommand sqlCommand = new SqlCommand(editRecord, dbConnection);
sqlCommand.ExecuteNonQuery();
}
dbConnection.Close();
}
}
}
}
finally
{
string addRecord = "INSERT INTO softwareLog VALUES('"
+ typeOS + "', '"
+ reportDate + "', '"
+ hardware + "', '"
+ occurrence + "', '"
+ shortDescription + "', '"
+ longDescription + "', '"
+ actionsTaken + "')";
SqlCommand sqlCommand = new SqlCommand(addRecord, dbConnection);
sqlCommand.ExecuteNonQuery();
}
string idString = "SELECT IDENT_CURRENT('softwareLog') AS reportID";
SqlCommand newID = new SqlCommand(idString, dbConnection);
SqlDataReader softwareReportRecord = newID.ExecuteReader();
softwareReportRecord.Read();
string reportID = Convert.ToString(softwareReportRecord["reportID"]);
softwareReportRecord.Close();
regMessage.Text += "<p>Sorry for your inconvience. We will be working on your problem ASAP. For reference your ID is </p>" + reportID;
dbConnection.Close();

You are missing too many "," in Update.
EDIT You have single quote inside string. You need to escape those quotes also:
string editRecord = "UPDATE softwareLog SET "
+ "typeOS='" + typeOS.Replace("'", "''") + "', "
+ "reportDate='" + reportDate + "', "
+ "hardware='" + hardware.Replace("'", "''") + "',"
+ "occurrence='" + occurrence.Replace("'", "''") + "',"
+ "shortDescription='" + shortDescription.Replace("'", "''") + "',"
+ "longDescription='" + longDescription + "',"
+ "actionsTaken='" + actionsTaken.Replace("'", "''") + "'"
+ "WHERE reportID= " + reportID ;
In insert you don't need quote for reportID:
string addRecord = "INSERT INTO softwareLog VALUES('"
+ typeOS.Replace("'", "''") + "', '"
+ reportDate + "', '"
+ hardware.Replace("'", "''") + "', '"
+ occurrence.Replace("'", "''") + "', '"
+ shortDescription.Replace("'", "''") + "', '"
+ longDescription.Replace("'", "''") + "', '"
+ actionsTaken.Replace("'", "''") + "')";

Chances are the data being passed to the query be terminating the string early. For many reasons (including this one, but also SQL injection), you should be using parameters instead of concatenation.

Try like this,
string editRecord = "UPDATE softwareLog SET "
+ "typeOS='" + typeOS + "', "
+ "reportDate='" + reportDate + "', "
+ "hardware='" + hardware + "',"
+ "occurrence='" + occurrence + "',"
+ "shortDescription='" + shortDescription + "',"
+ "longDescription='" + longDescription + "',"
+ "actionsTaken='" + actionsTaken + "'"
+ "WHERE reportID=" + reportID + "";
Can you please Add your Insert Statement too.
Remarks : It will better to use Parametrized SqlCommand or Store
Procedure to perform this type of operation.
If you supply value with ' to any field then, it will not work. Also check value you supply for ReportId.

In this example you should be using parameters as a precaution against SQL injection as others have mentioned.
But for other strings I suggest you look into string.Format() rather than concatenating everything. Would make that string so much easier to read.

Related

Column count doesn't match value count at row 1 when try to save into db

Im tring to save data on mysql db but i always get "Column count doesn't match value count at row 1"
I tried to recode this sql command, seen some videos about this but cant found nothing that work
string Insert =
"INSERT INTO db.pcs(Nome,Marca,Utilizador,Ram,CPU,Disco,TipoSO,SO,Licenca,TipoPC,ProgramaseLicenca) VALUES('"
+ nome + "," + marca + "," + user + "," + ram + ","
+ cpu + "," + disco + "," + tiposo + "," + so + ","
+ lice + "," + tipopc + "," + progs + "')";
using (MySqlConnection cn = new MySqlConnection(connst))
{
cn.Open();
MySqlCommand cmd = new MySqlCommand(Insert, cn);
try
{
if (cmd.ExecuteNonQuery() == 1)
{
pb1.Visible = true;
timer1.Start();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Its supose to add to db but on the try messagebox i get "Column count doesn't match value count at row 1"
I think you should make " ' " for each value
string Insert =
"INSERT INTO db.pcs (Nome,Marca,Utilizador,Ram,CPU,Disco,TipoSO,SO,Licenca,TipoPC,ProgramaseLicenca) VALUES('"
+ nome + "','" + marca + "','" + user + "','" + ram + "','"
+ cpu + "','" + disco + "','" + tiposo + "','" + so + "','"
+ lice + "','" + tipopc + "','" + progs + "')";
You set only one quote at the start and one at the end.
So it is only one value you set into your insert command.
Try this or use sqlparams:
string Insert =
"INSERT INTO db.pcs(Nome,Marca,Utilizador,Ram,CPU,Disco,TipoSO,SO,Licenca,TipoPC,ProgramaseLicenca) VALUES('"
+ nome + "', '" + marca + "', '" + user + "', '" + ram + "', '"
+ cpu + "', '" + disco + "', '" + tiposo + "', '" + so + "', '"
+ lice + "', '" + tipopc + "', '" + progs + "')";

How to insert Persian words into a SQL Server database?

I am just wondering how to insert Persian characters into my service-based database?
When I save my data it shows something like '???'.
I have checked such questions like this. But, the solutions were not useful.
private void button1_Click(object sender, EventArgs e)
{
objConnection.Open();
if (ctypeCheckBox.Checked == true)
st = 1;
else if (ctypeCheckBox.Checked == false)
st = 0;
string query = "INSERT INTO LectureTable(Cname, Cid, Ccredit, Csession, Ctype, CstartDate, CendDate, CstartTime, CendTime) VALUES('" + cnameTextBox.Text + "','" + cidTextBox.Text + "','" + ccreditTextBox.Text + "','" + csessionTextBox.Text + "','" + st + "', '" + cstartDateDateTimePicker.MinDate + "', '" + cendDateDateTimePicker.MaxDate + "', '" + cStartTimeBox.Text + "', '" + cEndTimeBox.Text + "')";
SqlDataAdapter SDA = new SqlDataAdapter(query, objConnection);
SDA.SelectCommand.ExecuteNonQuery();
MessageBox.Show("Inserted!");
objConnection.Close();
}
Two things:
Never ever combine your query string with values
"INSERT INTO LectureTable(Cname, Cid, Ccredit, Csession, Ctype, CstartDate, CendDate, CstartTime, CendTime) VALUES('" + cnameTextBox.Text + "','" + cidTextBox.Text + "','" + ccreditTextBox.Text + "','" + csessionTextBox.Text + "','" + st + "', '" + cstartDateDateTimePicker.MinDate + "', '" + cendDateDateTimePicker.MaxDate + "', '" + cStartTimeBox.Text + "', '" + cEndTimeBox.Text + "')";
Should be immediately replaced with
"INSERT INTO LectureTable(Cname, Cid, Ccredit, Csession, Ctype, CstartDate, CendDate, CstartTime, CendTime)
VALUES(#cname, #cid, #ccredit, #csession, #st, #cstartDateDate, #cendDate, #cStartTime, #cEndTimeB)";
and then you should use
SDA.SelectCommand.Parameters.AddWithValue("cname",cnameTextBox.Text);
for all parameters. This will save you from a lot of problems including SQL injection.
In the database your columns should have nvarchar data type.
Good luck
You should use SqlParameter .Giving example of only one parameter.You can add others as same way.
string query = "INSERT INTO LectureTable(Cname) VALUES(#name)";
using(SqlCommand cmd = new SqlCommand(query, SqlConnection))
{
SqlParameter param = new SqlParameter("#name", cnameTextBox.Text);
param.SqlDbType = SqlDbType.String;
cmd.Parameters.Add(param);
.....
}

Insert nullable int in c# using mysql

I have a table in mysql for users. Sometime user has a boss and sometime it don't.
So boss data type in nullable int(it is a foreign key, that's why nullable INT).
I was using following code and it was causing problem when boss value is null, producing following error "Incorrect integer value: '' for column 'boss_id' at row 1"
string query = " INSERT INTO " + databasename + ".system_user (" +
"`boss_id`, " +
"`name`, " +
"`user_name`, " +
"`password_2`, " +
"`designation`," +
"`digital_signature`," +
"`functional_role`," +
"`group_2`) " +
"VALUES ('" +
systemuser.Boss + "', '" +
systemuser.Name + "','" +
systemuser.UserName + "', '" +
systemuser.Password + "', '" +
systemuser.Designation + "', '" +
systemuser.DigitalSignature + "', '" +
systemuser.FunctionalRole + "', '" +
systemuser.Group + "');";
MySqlConnection conDataBase = new MySqlConnection(myconnection);
MySqlCommand cmdDataBase = new MySqlCommand(query, conDataBase);
MySqlDataReader myreader;
try
{
conDataBase.Open();
myreader = cmdDataBase.ExecuteReader();
conDataBase.Close();
return true;
}
catch (Exception ex)
{
conDataBase.Close();
MessageBox.Show(ex.Message);
return false;
}
So, i changed the code for string query as follow:
string query = "";
if(systemuser.Boss!=null)
{
query = " INSERT INTO " + databasename + ".system_user (" +
"`boss_id`, " +
"`name`, " +
"`user_name`, " +
"`password_2`, " +
"`designation`," +
"`digital_signature`," +
"`functional_role`," +
"`group_2`) " +
"VALUES ('" +
systemuser.Boss + "', '" +
systemuser.Name + "','" +
systemuser.UserName + "', '" +
systemuser.Password + "', '" +
systemuser.Designation + "', '" +
systemuser.DigitalSignature + "', '" +
systemuser.FunctionalRole + "', '" +
systemuser.Group + "');";
}
else
{
query = " INSERT INTO " + databasename + ".system_user (" +
"`name`, " +
"`user_name`, " +
"`password_2`, " +
"`designation`," +
"`digital_signature`," +
"`functional_role`," +
"`group_2`) " +
"VALUES ('" +
systemuser.Name + "','" +
systemuser.UserName + "', '" +
systemuser.Password + "', '" +
systemuser.Designation + "', '" +
systemuser.DigitalSignature + "', '" +
systemuser.FunctionalRole + "', '" +
systemuser.Group + "');";
}
It worked because, Mysql by default put null at the skipped values.
Now according to my scenario, I have to update boss_id from int to null and sometime from null to int. But my query always skip if value is null. Can you please help me in changing the insert statement in such a way that it would insert null value in boos(if its null) and don't just skip it.
Firstly, you should use parameters, it gives you a clean code and avoid injection.
You can use parameters like this:
string query = string.Format("INSERT INTO {0}.system_user (`boss_id`, `name`, `user_name`, `password_2`, `designation`, `digital_signature`, `functional_role`, `group_2`)" +
"VALUES (#boss_id, #name, #user_name, #password_2, #designation, #digital_signature, #functional_role, #group_2)", databasename);
MySqlConnection conDataBase = new MySqlConnection(myconnection);
MySqlCommand cmdDataBase = new MySqlCommand(query, conDataBase);
cmdDataBase.Parameters.AddWithValue("#boss_id", systemuser.Boss ?? (object)DBNull.Value);
cmdDataBase.Parameters.AddWithValue("#name", systemuser.Name);
cmdDataBase.Parameters.AddWithValue("#user_name", systemuser.UserName);
cmdDataBase.Parameters.AddWithValue("#password_2", systemuser.Password);
cmdDataBase.Parameters.AddWithValue("#designation", systemuser.Designation);
cmdDataBase.Parameters.AddWithValue("#digital_signature", systemuser.DigitalSignature);
cmdDataBase.Parameters.AddWithValue("#functional_role", systemuser.FunctionalRole);
cmdDataBase.Parameters.AddWithValue("#group_2", systemuser.Group);
Note "#boss_id", systemuser.Boss ?? (object)DBNull.Value, this is because you can not use null directly in the parameters.
UPDATE:
If you want to update or delete you can use parameters too:
You can write your queries like this:
string query = string.Format("UPDATE {0}.system_user SET `name` = #name WHERE `boss_id` = #boss_id", databasename);
or
string query = string.Format("DELETE FROM {0}.system_user WHERE `boss_id` = #boss_id", databasename);
For datetime columns you can see this question. It has very good answers.
You are encapsulating the value of Systemuser.Boss in single quotes, doesn't this indicate that you are trying to insert a string into an integer column?
string query = #"INSERT INTO {0}.system_user (
`boss_id`,
`name`,
`user_name`,
`password_2`,
`designation`,
`digital_signature`,
`functional_role`,
`group_2`)
VALUES
{1},
'{2}',
'{3}',
'{4}',
'{5}',
'{6}',
'{7}',
'{8}')
";
string formattedQuery = string.Format(query,
databasename, // {0}
Systemuser.Boss, // {1}
Systemuser.Name, // {2}
etc, etc);
EDIT: missed a part where you said 'when it was null'... you need to use:
(Systemuser.Boss ?? "NULL")

Error converting data type varchar to numeric in c# program

Please Help me out,This is my database table in sql-server
(empcode varchar(50)
firstname varchar(50)
lastname varchar(50)
gender varchar(50)
address varchar(50)
contactno numeric(18, 0)
bloodgroup varchar(50)
dateofbirth date
country varchar(50)
qid varchar(50)
passportno varchar(50)
passportexpiredate date
designation varchar(50)
doj date
doexpid date
pf_acc_no numeric(18, 0)
agreementstartdate date
agreementenddate date
department varchar(50)
basic_sal numeric(18, 0)
remarks varchar(50)
empimage image)
and I'm Trying to insert my data through c# windows forms but i'm getting error as "Error converting data type varchar to numeric."
Here below is my c# code
private void button2_Click(object sender, EventArgs e)
{
cn.Open();
if (!empid())
{
DialogResult d = new DialogResult();
d = MessageBox.Show("Do You Declare Yourself All The Information Of This Employee Is Correct To Save?", "Message", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if (d == DialogResult.Yes)
{
int i = 0;
SqlCommand cmd = new SqlCommand("INSERT INTO Employee(
empcode,firstname,lastname,gender,address,contactno,bloodgroup,
dateofbirth, country,qid,passportno,passportexpiredate,designation,
doj,doexpid,pf_acc_no, agreementstartdate,agreementenddate,
department,basic_sal,remarks,empimage)
VALUES('" + txtempcode.Text + "','" + txtfrstname.Text + "',
'" + txtlstname.Text + "','" + combogender.Text + "','" +
txtaddr.Text + "','" + txtcont.Text + "','" + txtblodgrp.Text + "', '" +
dob.Value.ToString("yyyy/MM/dd") + "' ,'" + txtcountry.Text + "','" + tqid.Text + "','" +
txtpassportno.Text + "', '" + passexpdate.Value.ToString("yyyy/MM/dd") + "' ,'" +
combodesig.Text + "', '" + doj.Value.ToString("yyyy/MM/dd") + "', '" + doexpqid.Value.ToString("yyyy/MM/dd") + "', '" +
txtqibacc.Text + "', '" + agreestartdate.Value.ToString("yyyy/MM/dd") + "','" + agreeenddate.Value.ToString("yyyy/MM/dd") + "' ,'" + combobranch.Text + "','" + txtnetsalary.Text + "','" + txtremark.Text + "',#empimage) ", cn);
MemoryStream stream = new MemoryStream();
pb1.Image.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg);
byte[] pic = stream.ToArray();
cmd.Parameters.AddWithValue("#empimage", pic);
i = cmd.ExecuteNonQuery();
if (i > 0)
{
MessageBox.Show("Successfully Inserted Employee Record" + i);
}
cn.Close();
showdata();
clear();
}
}
}
public bool empid()
{
using (SqlConnection con = new SqlConnection("Data Source=SAFIYA-PC;Initial Catalog=dbEmployee;User ID=sa;Password=sa$123"))
{
con.Open();
string query = "select empcode from Employee where empcode = '" + txtempcode.Text + "'";
SqlCommand cmd = new SqlCommand(query, con);
SqlDataReader dr;
dr = cmd.ExecuteReader();
while (dr.Read())
{
empCode = dr["empcode"].ToString();
if (empCode != "0")
{
MessageBox.Show("Id already Existed Please use Another One!!!!!!");
return false;
}
con.Close();
}
return true;
}
}
Edit: the comment below is quite right, the immediate issue is that you have single quotes around the data you are trying to put in the contactno numeric(18, 0) field which is telling SQL to interpret that value as a varchar.
Change "','" + txtcont.Text + "','" to "'," + txtcont.Text + ",'" (i.e. remove the single quotes either side of the text box value) and do the same for any other numeric fields.
However, as is mentioned in other responses, this general approach of concatenating together a sql command string is not recommended from a security point of view. The preferred option is to use a parametrised query.
Using a parametrised query will also make it easier to deal with any nullable fields, as per this example.
(Edited to correct the answer in response to comment from Steffen)
Why don't you use parameters? It prevents your code from SQL Injection and you don't have to convert values and code is much more readable. Look at sample (it is for select statement but the same works for insert/update/delete statement):
var connectionString = "some connection string";
using (var connection = new SqlConnection(connectionString)) {
connection.Open();
using (var command = new SqlCommand("SELECT * FROM Dogs1 WHERE Name LIKE #Name", connection)) {
command.Parameters.Add(new SqlParameter("Name", dogName));
var reader = command.ExecuteReader();
while (reader.Read()) {
int weight = reader.GetInt32(0);
string name = reader.GetString(1);
string breed = reader.GetString(2);
Console.WriteLine("Weight = {0}, Name = {1}, Breed = {2}",
weight,
name,
breed);
}
}
}
You are directly storing the text value of your controls in your numeric fields (contactno, pf_acc_no and basic_sal). Are the values really sql-string representations of numeric values?
I would try to convert them to numeric value
double dValue = 0.0;
double.TryParse(textBox1.Text, out dValue);
and then, in the sql string convert to their sql-string representations with dValue.ToString() or a special dedicated method.
As per your table structure, there are 3 fields that are of numeric datatype. These are - contactno, pf_acc_no and basic_sal
And the values for these fileds are txtcont.Text, txtqibacc.Text and txtnetsalary.Text respectively, And your are also putting ' around them, that is why they are being treated as varchar filed.
While constructing the sql statement, you should pass the values for these fields as numeric, which is to say without ' marks. So just remove ' before and after these fields and your query should work fine.
SqlCommand cmd = new SqlCommand("INSERT INTO Employee(
empcode,firstname,lastname,gender,address,contactno,bloodgroup,
dateofbirth, country,qid,passportno,passportexpiredate,designation,
doj,doexpid,pf_acc_no, agreementstartdate,agreementenddate,
department,basic_sal,remarks,empimage)
VALUES('" + txtempcode.Text + "','" + txtfrstname.Text + "',
'" + txtlstname.Text + "','" + combogender.Text + "','" +
txtaddr.Text + "'," + txtcont.Text + ",'" + txtblodgrp.Text + "', '" +
dob.Value.ToString("yyyy/MM/dd") + "' ,'" + txtcountry.Text + "','" + tqid.Text + "','" +
txtpassportno.Text + "', '" + passexpdate.Value.ToString("yyyy/MM/dd") + "' ,'" +
combodesig.Text + "', '" + doj.Value.ToString("yyyy/MM/dd") + "', '" + doexpqid.Value.ToString("yyyy/MM/dd") + "', " +
txtqibacc.Text + ", '" + agreestartdate.Value.ToString("yyyy/MM/dd") + "','" + agreeenddate.Value.ToString("yyyy/MM/dd") + "' ,'" + combobranch.Text + "'," + txtnetsalary.Text + ",'" + txtremark.Text + "',#empimage) ", cn);
In case you need to pass null to these numeric fields, use DBNull.Value as shown here -
Assign Null value to the Integer Column in the DataTable
Constructing queries like these are prone to SqlInjection, suggest to use parameterized queries instead.
Actually, your code is very vulnerable to SQL-injection attacks. But I don't changing your programming style; I'm changing just your insertion query:
SqlCommand cmd = new SqlCommand(#"
INSERT INTO Employee
(empcode, firstname, lastname, gender, address, contactno,
bloodgroup, dateofbirth, country, qid, passportno, passportexpiredate,
designation, doj, doexpid, pf_acc_no, agreementstartdate, agreementenddate,
department, basic_sal, remarks, empimage)
VALUES
('" + txtempcode.Text + "',
'" + txtfrstname.Text + "',
'" + txtlstname.Text + "',
'" + combogender.Text + "',
'" + txtaddr.Text + "',
" + txtcont.Text + ",
'" + txtblodgrp.Text + "',
'" + dob.Value.ToString("yyyy/MM/dd") + "' ,
'" + txtcountry.Text + "',
'" + tqid.Text + "',
" + txtpassportno.Text + ",
'" + passexpdate.Value.ToString("yyyy/MM/dd") + "' ,
'" + combodesig.Text + "',
'" + doj.Value.ToString("yyyy/MM/dd") + "',
'" + doexpqid.Value.ToString("yyyy/MM/dd") + "',
'" + txtqibacc.Text + "',
'" + agreestartdate.Value.ToString("yyyy/MM/dd") + "',
'" + agreeenddate.Value.ToString("yyyy/MM/dd") + "' ,
'" + combobranch.Text + "',
" + txtnetsalary.Text + ",
'" + txtremark.Text + "',
#empimage) ", cn);

How to save a picture to an access database table?

I am using this code to save a picture into an access database table:
byte[] fromPath = File.ReadAllBytes(Picture_Path);
byte[] fromPath2 = File.ReadAllBytes(BacksidePicture_Path);
con.Open();
string query = "Insert Into DML_Books_List (" +
"ID,ISNBORCode, Title, Donor, DocType, Edition, Author1, Author2, Author3, " +
"Author4, Translator, Publisher, Subject, USubject, Shelf, Cost, " +
"Language, Pages, Image, BImage, Description, Date) VALUES ('" +
"2" + "','" + ISNB_AddBook_Books_TXT.Text + "', '" +
Title_AddBook_Books_TXT.Text +
"', '" + Donor_AddBook_Books_TXT.Text + "', '" +
DocType_AddBook_Books_CBE.SelectedItem + "', '" +
Edition_AddBook_Books_TXT.Text + "', '" +
Author1_AddBook_Books_TXT.Text + "', '" +
Author2_AddBook_Books_TXT.Text + "', '" +
Author3_AddBook_Books_TXT.Text + "', '" +
Author4_AddBook_Books_TXT.Text + "', '" +
Translator_AddBook_Books_TXT.Text + "', '" +
Publisher_AddBook_Books_CBE.SelectedItem + "', '" +
Subject_AddBook_Books_CBE.SelectedItem + "', '" +
USubject_AddBook_Books_CBE.SelectedItem + "', '" +
Shelf_AddBook_Books_CBE.SelectedItem + "', '" +
Cost_AddBook_Books_TXT.Text + "', '" +
Language_AddBook_Books_CBE.SelectedItem + "', '" +
Pages_AddBook_Books_TXT.Text + "', '" +
#fromPath + "', '" + #fromPath2 + "', '" +
Description_AddBook_Books_MemoEdit.Text + "', '" +
Date_AddBook_Books_TXT.Text + "')";
OleDbCommand myCommand = new OleDbCommand();
myCommand.CommandText = query;
myCommand.Connection = con;
myCommand.ExecuteNonQuery();
con.Close();
But it has some problems.
Please Help Me solve this problem.
Thank you
OleDb.OleDbConnection cn = new OleDb.OleDbConnection();
cn.ConnectionString = "Provider=Microsoft.Jet.OleDb.4.0; Data Source=" + Application.StartupPath + "\\data.mdb";
cn.Open();
byte[] arrImage = null;
string strImage = null;
IO.MemoryStream myMs = new IO.MemoryStream();
//
if ((this.picPhoto.Image != null)) {
this.picPhoto.Image.Save(myMs, this.picPhoto.Image.RawFormat);
arrImage = myMs.GetBuffer;
strImage = "?";
} else {
arrImage = null;
strImage = "NULL";
}
OleDb.OleDbCommand myCmd = new OleDb.OleDbCommand();
myCmd.Connection = cn;
myCmd.CommandText = "INSERT INTO tblstudent(stdid, [name], photo) " + " VALUES(" + this.txtID.Text + ",'" + this.txtName.Text + "'," + strImage + ")";
if (strImage == "?") {
myCmd.Parameters.Add(strImage, OleDb.OleDbType.Binary).Value = arrImage;
}
Interaction.MsgBox("Data save successfully!");
myCmd.ExecuteNonQuery();
cn.Close();
Source
use parameters like below code:
Assume you have two columns in your table called ID and Image. Now you going to insert data using SQL parameters
you need SQL statement like
Insert Into DML_Books_List(ID, [Image]) values (#id, #image)
#id and #image are the given names for parameters. You can set the parameter values by parameter name.
var pic = File.ReadAllBytes(yourFileName);
using(OleDbConnection con = new OleDbConnection(constr))
using(OleDbCommand cmd = new OleDbCommand("Insert Into DML_Books_List(ID, [Image]) values (#id, #image)", con))
{
con.Open();
cmd.Parameters.AddWithValue("#id", TextBox1.Text);
cmd.Parameters.AddWithValue("#image", pic);
cmd.ExecuteNonQuery();
}
Use parametrized query..
OleDbConnection connection = new OleDbConnection(#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=database");
OleDbCommand command = connection.CreateCommand();
imageData = ReadByteArrayFromFile(#"c:\test.jpg");
command.CommandText = "Insert into SomeTable (Name, ImageData) VALUES (#Name, #Img)"
command.Parameters.AddWithValue("#Name", "theName");
command.Parameters.AddWithValue("#Img", imageData);
command.ExecuteNonQuery();

Categories

Resources