I am trying to insert in database Ms Access 2007 . First i get all the file name from folder then copy that file name in database .Here is my Database screenshot.
This is my code
string some = "Nothing";
Response.Write(v);
string[] filePaths = Directory.GetFiles(Server.MapPath("~/Gallery/GalleryImage/" + v));
int a =0;
OleDbCommand cmd = new OleDbCommand();
OleDbConnection mycon = new OleDbConnection();
mycon.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\AGENTJ.AGENTJ-PC\Documents\Visual Studio 2010\WebSites\mfaridalam\App_Data\mfaridalam1.accdb";
cmd = mycon.CreateCommand();
mycon.Open();
foreach (string item in filePaths)
{
a++;
string filename = Path.GetFileName(item);
string ips = 00 + a.ToString();
cmd.CommandText = "INSERT INTO [Image] ([Image],[Sort],[Created],[Albumid],[Description],[title])VALUES(" + filename + "," + ips + "," + some + "," +
v + "," + some + "," + some + ");";
int temp = cmd.ExecuteNonQuery();
if (temp > 0)
{
Response.Write("Writing is complete, Success!");
}
else
{
Response.Write("Application Error, Try Again!");
}
Response.Write(filename+ "<br/>");
}
mycon.Close();
cmd.Dispose();
mycon.Dispose();
I am Getting this error
No value given for one or more required parameters.
In line Line 42: int temp = cmd.ExecuteNonQuery();
If you had used a parameterized query this error would never be seen. The problem is in your string concatenation that lacks of quotes around the string passed for the values in every text/memo field present in your table.
A parameterized query could require more typing but is more readable and will avoid error in parsing values for strings, dates, decimals etc.... (and that big problem called Sql Injection )
cmd.CommandText = "INSERT INTO [Image] ([Image],[Sort],[Created],[Albumid]," +
"[Description],[title])VALUES(?,?,?,?,?,?)";
cmd.Parameters.AddWithValue("#p1",filename);
cmd.Parameters.AddWithValue("#p2",ips);
cmd.Parameters.AddWithValue("#p3",some);
cmd.Parameters.AddWithValue("#p4",v);
cmd.Parameters.AddWithValue("#p5",some);
cmd.Parameters.AddWithValue("#p6",some);
int temp = cmd.ExecuteNonQuery();
Related
I want to insert new row in my database from user input, i use C# and sql insert syntax. My problem is when i run a program all field compltely fill except text value (name of the product) which fill with another number (price) i check the syntax and the code but it's never work.
public DataBaseManager (string DataBaseFilename)
{
strFileName = DataBaseFilename;
strFileNamenopath = System.IO.Path.GetFileName(strFileName);
strAccessConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + System.IO.Path.GetFullPath(strFileName).Replace(System.IO.Path.GetFileName(strFileName), "") + "; Extended Properties=dBase III;Mode=ReadWrite";
conn = new OleDbConnection(strAccessConn);
conn.Open();
}
public void AddData(string Column, string value)
{
try
{
int i = 0;
char[] delimiterChars = { ','};
queryCutting = #"INSERT INTO [" + strFileNamenopath + "] ( " + Column + " ) VALUES ( " + value + " )";
OleDbCommand cmd = new OleDbCommand(queryCutting, conn);
string[] _valseperated = value.Split(delimiterChars);
string[] _columnsbase = Column.Split(delimiterChars);
foreach (string str in _columnsbase )
{
cmd.Parameters.AddWithValue(str,SqlDbType.VarChar).Value = _valseperated[i];
i++;
}
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
private void AddnewCode_Buttion_Click(object sender, RoutedEventArgs e)
{
_productBase.AddData("code, pv1, achat, designat", "123456789" + ", " + Textbox_Achat.Text + ", " + Textbox_Achat.Text +", " + Produitsnom_TextBox.Text);
}
Value of column represent the column name in databse , value is the text box value.
Column = "code, pv1, achat, designat";
Value = "123456789, 10, 10, Productname";
value of queryCutting
queryCutting = "INSERT INTO [produits.dbf] ( code, pv1, achat, designat ) VALUES ( 123456789, 540, 120, NewProduct)"
I think I have understood your problem. You set the Value string directly in the query text so you should get this result
"INSERT INTO [theFolderName] (code, pv1, achat, designat)
VALUES ( 123456789, 10, 10, Productname )";
The first three values are accepted as correct values for the numeric fields and no parameter is taken in consideration for these fields, but when the parser reaches the ProductName "value" it cannot use as a value because it is not a inside quotes. So it thinks it is a parameter and searches the Parameters collection. Because in OleDb parameters are positional, it takes the first parameter and passes its value to the OleDbCommand. And the first parameter is the Code.
This should solve the problem. Don't give a parameter name (OleDb doesn't care) and let the OleDbCommand use the complete set of parameters given in the exact order expected
public void AddData(string Column, string value)
{
try
{
char[] delimiterChars = { ','};
// Query text is incomplete, we complete it inside the loop
queryCutting = #"INSERT INTO [" + strFileNamenopath + #"]
( " + Column + " ) VALUES ( ";
// The query and the connection will be set after the loop
OleDbCommand cmd = new OleDbCommand();
string[] _valseperated = value.Split(delimiterChars);
string[] _columnsbase = Column.Split(delimiterChars);
foreach (string str in _columnsbase )
{
// The second parameter in AddWithValue is the Value not the type.
cmd.Parameters.AddWithValue(str, _valseperated[i]);
// Add a placeholder for each parameter
queryCutting += "?,";
}
// Remove the ending colon an close the paren on the query text
queryCutting = queryCutting.Substring(queryCutting.Length-1) + ")";
cmd.CommandText = queryCutting;
cmd.Connection = conn;
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Notice that this code doesn't solve your Sql Injection problem. You should be absolutely sure that your user doesn't type itself neither the file name/folder neither the name of the columns and choose these values from a whitelisted set of values
I solved the problem by add insering Produitsnom_TextBox.Text betwwen qutes like this
_productBase.AddData("code, designat ,pv1, achat", "123456789" + ", " + "' " +Produitsnom_TextBox.Text + "'" + ", " + Vente_TextBox.Text + ", " + Textbox_Achat.Text );
also i removed the parametes part.
public void AddData(string Column, string value)
{
try
{
int i = -1;
char[] delimiterChars = { ',' };
queryCutting = #"INSERT INTO [" + strFileNamenopath + "] ( " + Column + " ) VALUES ( " + value + " )";
OleDbCommand cmd = new OleDbCommand(queryCutting, conn);
MessageBox.Show(queryCutting);
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
try
{
int i = 0;
using (SqlConnection sqlCon = new SqlConnection(Form1.connectionString))
{
string commandString = "INSERT INTO Logindetail (Account,ID,Logint,Logoutt) values ('" + acc + "'," + textbxID.Text + "," + null + ", SYSDATETIME()" + ");";
// MessageBox.Show(commandString);
SqlCommand sqlCmd = new SqlCommand(commandString, sqlCon);
sqlCon.Open();
SqlDataReader dr = sqlCmd.ExecuteReader();
i = 1;
if (i == 0)
{
MessageBox.Show("Error in Logging In!", "Error");
}
MessageBox.Show("Successfully Logged In");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
I'm making a LoginForm for a Project.I have created a table which shows the LoginDetails(Account,ID,LoginTime,LogoutTime).But when I run the Program,it doesn't runs successfully.I face an error which is in Pic-2.When I remove sql 'data reader',the program runs without displaying the error.
When you concatenate a null it basically adds nothing to the string, so this code:
string commandString = "INSERT INTO Logindetail (Account,ID,Logint,Logoutt) values ('" + acc + "'," + textbxID.Text + "," + null + ", SYSDATETIME()" + ");";
results of this string, and as you can see it has an extra comma, that causes the exception:
"INSERT INTO Logindetail (Account,ID,Logint,Logoutt) values ('acc',textbxID,, SYSDATETIME());"
If you want to add NULL to the query it has to be a string, so do this instead:
string commandString = "INSERT INTO Logindetail (Account,ID,Logint,Logoutt) values ('" + acc + "'," + textbxID + ", NULL , SYSDATETIME()" + ");";
And you are using ExecuteReader instead of ExecuteNonQuery. You cannot use ExecuteReader for inserting rows to the DB.
Also, as someone mentioned in the other answer, you better do it with parametes to avoid SQL Injections.
I keep on having this error "Incorrect datetime value '2/1/16 7:22:00 AM'. I am sending a datetime value to a datetime data type column in mysql.
This is my code :
String AMTime =(AMHour.Text + ':' + AMMinute.Text).ToString();
am = Convert.ToDateTime(AMTime);
// string am = AMTimeConvert.ToString("HH:mm:ss");
String NNTime = (NNHour.Text + ':' + NNHour.Text).ToString();
nn = Convert.ToDateTime(NNTime);
// string nn = NNTimeConvert.ToString("HH:mm:ss");
String PMTime = (PMHour.Text + ':' + PMMinute.Text).ToString();
pm = Convert.ToDateTime(PMTime);
// string pm = PMTimeConvert.ToString("HH:mm:ss");
if (Generic != null || Brand != null || ContainerNum != "" || status != "")
{
result = database.AddMedicinePrescription(PrescribedDays,Dosage,numprescribed,NumofIntake,am,nn,pm);
}
This is the code that is to connect to my db
public bool AddMedicinePrescription(int PrescribedDays, int Dosage, int numprescribed, int NumofIntake, DateTime am, DateTime nn, DateTime pm)
{
sqlstring = "INSERT INTO hdmedicinedispenser (PresDayOfIntake, PresNoOfMedicine, DosPerIntake, NumOfIntake,AMIntake, NNIntake, PMIntake)" + "VALUE (" + PrescribedDays + ", " + numprescribed + ", " + Dosage + ", " + NumofIntake + ", '"+ am +"', '"+ nn +"', '"+ pm +"' ) ";
try
{
connect.Open();
MySqlCommand cmd = new MySqlCommand(sqlstring, connect);
MySqlDataAdapter adapter = new MySqlDataAdapter(cmd);
DataTable dt = new DataTable();
adapter.Fill(dt);
connect.Close();
return true;
}
catch (Exception error)
{
MessageBox.Show("Warning 2: " + error.Message);
return false;
}
Because you try to add your DateTime values as a character with single quotes like '"+ am +"'
You need to delete all single quotes for your DateTime values.
But more important, stop the string concatenation when you build your commands. You should always use parameterized queries. This kind of string concatenations are open for SQL Injection attacks.
Also you need ExecuteNonQuery instead of using a MySqlDataAdapter since INSERT statement does not return any data. It just inserts your value.
using(var connect = new MySqlConnection(conString))
using(var cmd = connect.CreateCommand())
{
cmd.CommandText = #"INSERT INTO hdmedicinedispenser (PresDayOfIntake, PresNoOfMedicine, DosPerIntake, NumOfIntake,AMIntake, NNIntake, PMIntake)
VALUE (#PrescribedDays, #numprescribed, #Dosage, #NumofIntake, #am, #nn, #pm)";
// Add your parameters with specify their types and size.
connect.Open();
cmd.ExecuteNonQuery();
}
Also you might need to read: Bad habits to kick : choosing the wrong data type
How would I go about import/inserting a .DAT file into the database by calling a procedure?
Here's what my file would look like and it has to go into the database in this format.
50 4411902304 1 3 441192304 01/02/2013
Would the process be the same for .DAT file as to xml file?
Here's what I have for xml
SqlConnection myConnection = new SqlConnection("user id=name;" +
"password=password;server=servername;" +
"Trusted_Connection=yes;" +
"database=database; " +
"connection timeout=30");
var conn = new SqlConnection();
conn.ConnectionString = "user id=idName;" +
"password=password;" + "server=servername;" + "Trusted_Connection=yes;" + "database=databasename; " + "connection timeout=30";
string filePath = "C:/TestData2.xml";
string xml = File.ReadAllText(filePath);
using (SqlConnection con = new SqlConnection(conn.ConnectionString))
{
using (SqlCommand cmd = new SqlCommand("procedureName"))
{
cmd.Connection = con;
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#x", xml);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("done");
}
}
What happens is that XML is a new technology compared to the old flat file (DAT).
XML is a markup format file and there are functions implemented to make easier the importing tasks.
Flat file are older, so a different approach is needed.
You can use the bcp (bulk copy program) to import files to SQL Server or the SSIS Import options.
Or, you can also use:
System.IO.StreamReader file = new System.IO.StreamReader(#"c:\data\TestData2.dat");
int counter = 0;
while ((line = (file.ReadLine())) != null){...}
And parsing each line using the Split command.
string[] fields= line.Split(' ');
string a = fields[0];
string b = fields[1];
string c = fields[2];
and then execute a command to insert each line:
string sqlCommandtoInsert= "INSERT INTO [Table] (Tablefield1, Tablefield2, Tablefield3) VALUES (" + a + ", " + b + ", '" + c + "');";
cmd.CommandText = sqlCommandtoInsert;
cmd.ExecuteNonQuery();
Inserting each record in your table.
i was trying to update two tables at once, but i got some syntax error on update code could u give me some idea? the insert code works perfect and i tried to copy the insert code and edit on update button clicked
here is my code
private void button2_Click(object sender, EventArgs e)
{
System.Data.OleDb.OleDbConnection conn = new System.Data.OleDb.OleDbConnection();
conn.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;" +
#"Data source= C:\Users\user\Documents\Visual Studio 2010\Projects\WindowsFormsApplication1\WindowsFormsApplication1\crt_db.accdb";
try
{
conn.Open();
String Name = txtName.Text.ToString();
String AR = txtAr.Text.ToString();
String Wereda = txtWereda.Text.ToString();
String Kebele = txtKebele.Text.ToString();
String House_No = txtHouse.Text.ToString();
String P_O_BOX = txtPobox.Text.ToString();
String Tel = txtTel.Text.ToString();
String Fax = txtFax.Text.ToString();
String Email = txtEmail.Text.ToString();
String Item = txtItem.Text.ToString();
String Dep = txtDep.Text.ToString();
String k = "not renwed";
String Remark = txtRemark.Text.ToString();
String Type = txtType.Text.ToString();
String Brand = txtBrand.Text.ToString();
String License_No = txtlicense.Text.ToString();
String Date_issued = txtDate.Text.ToString();
String my_querry = "update crtPro set Name='" + Name + "',AR='" + AR + "',Wereda='" + Wereda + "',Kebele='" + Kebele + "',House_No='" + House_No + "',P_O_BOX='" + P_O_BOX + "',Tel='" + Tel + "',Fax='" + Fax + "',Email='" + Email + "',Item='" + Item + "',Dep='" + Dep + "','" + k + "',Remark='" + Remark + "' where Name='" + Name + "' ";
OleDbCommand cmd = new OleDbCommand(my_querry, conn);
cmd.ExecuteNonQuery();
String my_querry1 = "SELECT max(PID) FROM crtPro";
OleDbCommand cmd1 = new OleDbCommand(my_querry1, conn);
string var = cmd1.ExecuteScalar().ToString();
String ki = txtStatus.Text.ToString();
String my_querry2 = "update crtItemLicense set PID=" + var + ",Type='" + Type + "',Brand='" + Brand + "',License_No='" + License_No + "',Date_issued='" + Date_issued + "' where PID=" + var + "";
OleDbCommand cmd2 = new OleDbCommand(my_querry2, conn);
cmd2.ExecuteNonQuery();
MessageBox.Show("Message added succesfully");
}
catch (Exception ex)
{
MessageBox.Show("Failed due to" + ex.Message);
}
finally
{
conn.Close();
}
The most likely problem based on the little information given (what database are you using for example - SQL Server 2012?), is that the datatype you are providing in the concatenated dynamic sql does not match the datatype of the column in the database. You've surrounded each value with quotes - which means it will be interpreted as a varchar. If you've got a date value in the wrong format (ie if Date_Issued is a date column) or if it is a number column, then it will error.
The solution is to replace your dynamic SQL with a parameterized query eg:
String my_querry = "update crtPro set Name=#name, AR=#ar, Wereda=#Wereda, etc ...";
OleDbCommand cmd = new OleDbCommand(my_querry, conn);
cmd.Parameters.Clear();
cmd.Parameters.AddWithValue("#name", Name);
cmd.Parameters.AddWithValue("#myParam", Convert.ToDateTime(txtDate.Text.Trim()));
...
cmd.ExecuteNonQuery();
You can read about it further here
PS Make sure your parameters are in the same order as they are used in the SQL, because oledbcommand doesn't actually care what you call them. see here