After searching for about an hour it appears this is the correct way to use the oledb libary to insert a record to an access database however it doesnt work for me , HELP...
InitializeComponent();
System.Data.OleDb.OleDbConnection conn = new
System.Data.OleDb.OleDbConnection();
// TODO: Modify the connection string and include any
// additional required properties for your database.
conn.ConnectionString = #"Provider = Microsoft.ACE.OLEDB.12.0; Data Source = \\crd-a555-015.occ.local\c$\Users\james.piper\Documents\Visual Studio 2015\Projects\Project V1\Project Database.accdb";
try
{
OleDbCommand cmd = new OleDbCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "INSERT INTO Work_Done (employee,client,project,task,hours)" + " VALUES (#employee,#client,#project,#task,#hours)";
cmd.Parameters.AddWithValue("#employee", user.employee);
cmd.Parameters.AddWithValue("#client", listBox1.SelectedItem.ToString());
cmd.Parameters.AddWithValue("#project", listBox2.SelectedItem.ToString());
cmd.Parameters.AddWithValue("#task", listBox3.SelectedItem.ToString());
cmd.Parameters.AddWithValue("#hours", listBox4.SelectedItem.ToString());
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
}
catch (Exception ex)
{
MessageBox.Show("sql insert fail");
}
I would write this code like this:
var connectionString = #"Provider = Microsoft.ACE.OLEDB.12.0; Data Source = \\crd-a555-015.occ.local\c$\Users\james.piper\Documents\Visual Studio 2015\Projects\Project V1\Project Database.accdb";
var query = "INSERT INTO Work_Done (employee,client,project,task,hours) VALUES (#employee,#client,#project,#task,#hours)";
using (var conn = new OleDbConnection(connectionString))
{
using(var cmd = new OleDbCommand(query, conn))
{
// No need to specifiy command type, since CommandType.Text is the default
// I'm assuming, of course, your parameter data types. You should change them if my assumptions are wrong.
cmd.Parameters.Add("#employee", OleDbType.Integer).Value = user.employee;
cmd.Parameters.Add("#client", OleDbType.Integer).Value = Convert.ToInt32(listBox1.SelectedItem);
cmd.Parameters.Add("#project", OleDbType.Integer).Value = Convert.ToInt32(listBox2.SelectedItem);
cmd.Parameters.Add("#task", OleDbType.Integer).Value = Convert.ToInt32(listBox3.SelectedItem);
cmd.Parameters.Add("#hours", OleDbType.Integer).Value = Convert.ToInt32(listBox4.SelectedItem);
try
{
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
}
catch (Exception ex)
{
MessageBox.Show($"sql insert fail: {ex}");
}
}
}
The major changes are these:
use the Using statement for each instance of a class that implements the IDisposable interface.
Using constructors with parameters to make the code shorter (and more readable, IMHO).
Note that the constructor of the OleDbCommand also has the OleDbConnection object. In your code, you didn't specify the active connection to the command.
Adding parameters with Add and not AddWithValue. Read this blog post to find out why.
Related
I'm trying to delete record from data base MSSQL by entering the ID and hit delete btn. i didn't get any error and it give recorded deleted successful but once i check database i see the record doesn't deleted
protected void btnDelete_Click(object sender, EventArgs e)
{
try
{
if (txtImgID.Text == "")
{
Response.Write("Enter Image Id To Delete");
}
else
{
SqlCommand cmd = new SqlCommand();
SqlConnection con = new SqlConnection();
con = new SqlConnection(ConfigurationManager.ConnectionStrings["GMSConnectionString"].ConnectionString);
con.Open();
cmd = new SqlCommand("delete from certf where id=" + txtImgID.Text + "", con);
lblsubmitt.Text = "Data Deleted Sucessfully";
}
}
catch (Exception)
{
lblsubmitt.Text = "You haven't Submited any data";
}
}
var idToDelete = int.Parse(txtImgID.Text); // this is not necessary if the data type in the DB is actually a string
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["GMSConnectionString"].ConnectionString))
using (SqlCommand cmd = new SqlCommand("DELETE FROM [certf] WHERE id = #id", con))
{
// I am assuming that id is an integer but if it is a varchar/string then use the line below this one
// cmd.Parameters.Add("#id", SqlDbType.VarChar, 100).Value = txtImgID.Text;
cmd.Parameters.Add("#id", SqlDbType.Int32).Value = idToDelete;
cmd.ExecuteNonQuery();
}
You need to call ExecuteNonQuery which executes the query against the database.
Always use parameters instead of string concatenation in your queries. It guards against sql injection and ensures you never has issues with strings that contain escape characters.
I did not include any error handling or return messages but do note that you are throwing away all the good stuff in your excetion handler's catch block, you will never know why a query failed after this has executed.
I'm trying something out but cant figure it out. So what i'm trying is that if the user inputs something inside txtISN and it already exists inside of the database, the record wont be inserted. I also want a error msg to pop up when a record wasnt inserted and when a record is inserted I want an message to pop up saying that the record was inserted succesfully.
Thanks for the help y'all!
string _connStr = #"Data Source = EJQ7FRN; Initial Catalog = BES; Integrated Security = True";
string _query = "INSERT INTO [BES_S] (ISN,Titel,Name) values (#ISN,#Titel,#Name)";
using (SqlConnection conn = new SqlConnection(_connStr))
{
using (SqlCommand comm = new SqlCommand())
{
comm.Connection = conn;
comm.CommandType = CommandType.Text;
comm.CommandText = _query;
comm.Parameters.AddWithValue("#ISN", txtISN.Text);
comm.Parameters.AddWithValue("#Titel",txtTitel.Text);
comm.Parameters.AddWithValue("#Name", txtName.Text);
try
{
conn.Open();
comm.ExecuteNonQuery();
}
catch (SqlException ex)
{
}
}
}
You need to change your query a bit, but you can use MySql's DUAL keyword to do this:
string _connStr = #"Data Source = EJQ7FRN; Initial Catalog = BES; Integrated Security = True";
string _query = "INSERT INTO [BES_S] (ISN,Titel,Name) ";
_query = _query + " SELECT #ISN, #Titel, #Name FROM DUAL";
_query = _query + " WHERE NOT EXISTS (SELECT ISN WHERE ISN=#ISN)";
using (SqlConnection conn = new SqlConnection(_connStr))
{
using (SqlCommand comm = new SqlCommand())
{
comm.Connection = conn;
comm.CommandType = CommandType.Text;
comm.CommandText = _query;
comm.Parameters.AddWithValue("#ISN", txtISN.Text);
comm.Parameters.AddWithValue("#Titel",txtTitel.Text);
comm.Parameters.AddWithValue("#Name", txtName.Text);
try
{
conn.Open();
comm.ExecuteNonQuery();
}
catch (SqlException ex)
{
}
}
}
DUAL is like a dummy table that you can use to SELECT from.
Let the database take care of this using a unique constraint/index:
alter table bes_s add constraint unq_bes_ISN unique (ISN);
This will cause the database to generate an error if a duplicate ISN is inserted. You can put one or more columns for the unique constraint (in case this single column is not the exact definition of uniqueness).
So I want to create a line graph with data from a MySQL table and I've managed to draw one using the code below.
However, I want to pass a variable 'moduleID' to the MySQL query and I have done so, however, I'm not sure if this is the most appropriate way to do so. Should I pass a parameter instead and if so, how do I do that?
protected void chart(int moduleID)
{
string connStr = ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString;
MySqlConnection conn = new MySqlConnection(connStr);
string comm = "SELECT * FROM scores WHERE module_id=" + moduleID.ToString();
MySqlDataAdapter dataAdapter = new MySqlDataAdapter(comm, conn);
DataSet ds = new DataSet();
Chart1.ChartAreas["ChartArea1"].AxisX.MajorGrid.Enabled = false;
Chart1.ChartAreas["ChartArea1"].AxisY.MajorGrid.Enabled = false;
Chart1.ChartAreas["ChartArea1"].AxisX.Minimum = 1;
Chart1.ChartAreas["ChartArea1"].AxisX.LabelStyle.Enabled = false;
Chart1.ChartAreas["ChartArea1"].AxisX.Title = "time";
Chart1.ChartAreas["ChartArea1"].AxisY.Minimum = 0;
Chart1.ChartAreas["ChartArea1"].AxisY.Maximum = 100;
Chart1.ChartAreas["ChartArea1"].AxisY.Title = "%";
Chart1.ChartAreas["ChartArea1"].AxisY.TextOrientation = TextOrientation.Horizontal;
try
{
conn.Open();
dataAdapter.Fill(ds);
Chart1.DataSource = ds;
Chart1.Series["Series1"].YValueMembers = "score";
Chart1.DataBind();
}
catch
{
lblError.Text = "Database connection error. Unable to obtain data at the moment.";
}
finally
{
conn.Close();
}
}
You are right. Concatenating strings to form a query is prone to SQL injection. Use parameters like:
string comm = "SELECT * FROM scores WHERE module_id=#module_id";
MySqlCommand mySqlCommand = new MySqlCommand(comm,conn);
mySqlCommand.Parameters.Add(new MySqlParameter("#module_id", module_id));
MySqlDataAdapter dataAdapter = new MySqlDataAdapter(mySqlCommand);
You should also enclose your connection and command object with using statement. This will ensure proper disposal of resource.
Also an empty catch is very rarely useful. You should catch specific exception first and then the base exception Exception in an object. Use that object to log the exception information or show in your error message. This will provide you help in debugging your application.
Step1: Create stored Procedure
CREATE PROCEDURE SelectScore
(#moduleID NCHAR(50))AS
SELECT * FROM scores WHERE module_id=#moduleID
Step2: Call the stored Procedure from Code
string connStr = ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString;
using (SqlConnection conn = new SqlConnection(connStr )) {
conn.Open();
// 1. create a command object identifying the stored procedure
SqlCommand cmd = new SqlCommand("SelectScore", conn);
// 2. set the command object so it knows to execute a stored procedure
cmd.CommandType = CommandType.StoredProcedure;
// 3. add parameter to command, which will be passed to the stored procedure
cmd.Parameters.Add(new SqlParameter("#moduleID ", moduleID ));
// execute the command
using (SqlDataReader rdr = cmd.ExecuteReader()) {
// iterate through results, printing each to console
while (rdr.Read())
{
..
}
}
}
I am having a problem with an Output parameter in C#/Oracle. I have isolated the code that I need to get working.
This is part of a much larger SQL statement, so do not worry too much if it doesn't make sense. In short I need to copy a row, give it a new ID and return that new ID. I tried using "RETURNING" which did not work. I see no reason why the code below should not work, but I'm getting an "ORA-01036: illegal variable name/number" error. Can anyone see what I'm doing wrong?
using (OracleConnection conn = new OracleConnection(connString))
{
// Open connection and create command.
conn.Open();
using (OracleCommand cmd = new OracleCommand())
{
cmd.Connection = conn;
cmd.CommandType = CommandType.Text;
cmd.Parameters.Add("outValue", OracleType.Int32).Direction = ParameterDirection.Output;
cmd.CommandText = "SELECT seq.nextval INTO :outValue FROM dual";
try
{
cmd.ExecuteNonQuery();
}
catch (Exception e)
{
// This is just to see the exception when it fails.
}
}
}
The name of the parameter doesn't match.
cmd.Parameters.Add(":outValue", OracleType.Int32).Direction.......;
^
I have also seen this variation on the query syntax
"BEGIN SELECT seq.nextval INTO :outValue FROM dual END;"
You are using named parameters. Try setting:
cmd.BindByName = true;
Have you tried 'returning' keyword like this?
This code works for me.
using (OracleConnection conn = new OracleConnection(connString))
{
// Open connection and create command.
conn.Open();
using (OracleCommand cmd = new OracleCommand())
{
cmd.Connection = conn;
cmd.CommandType = CommandType.Text;
cmd.Parameters.Add("outValue", OracleType.Int32).Direction = ParameterDirection.Output;
cmd.CommandText = "insert into table (id, value) values (seq.nextval, 'value') returning id into :outValue";
cmd.ExecuteNonQuery();
}
}
I am new to ADO.net. I actually created a sample database and a sample stored procedure. I am very new to this concept. I am not sure of how to make the connection to the database from a C# windows application. Please guide me with some help or sample to do the same.
Something like this... (assuming you'll be passing in a Person object)
public int Insert(Person person)
{
SqlConnection conn = new SqlConnection(connStr);
conn.Open();
SqlCommand dCmd = new SqlCommand("InsertData", conn);
dCmd.CommandType = CommandType.StoredProcedure;
try
{
dCmd.Parameters.AddWithValue("#firstName", person.FirstName);
dCmd.Parameters.AddWithValue("#lastName", person.LastName);
dCmd.Parameters.AddWithValue("#age", person.Age);
return dCmd.ExecuteNonQuery();
}
catch
{
throw;
}
finally
{
dCmd.Dispose();
conn.Close();
conn.Dispose();
}
}
It sounds like you are looking for a tutorial on ADO.NET.
Here is one about straight ADO.NET.
Here is another one about LINQ to SQL.
This is the usual pattern (it might be a bit different for different databases, Sql Server does not require you to specify the parameters in the command text, but Oracle does, and in Oracle, parameters are prefixed with : not with #)
using(var command = yourConnection.CreateCommand())
{
command.CommandText = "YOUR_SP_CALL(#PAR1, #PAR2)";
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add(new OdbcParameter("#PAR1", "lol"));
command.Parameters.Add(new OdbcParameter("#PAR2", 1337));
command.ExecuteNonQuery();
}
Something like this:
var connectionString = ConfigurationManager.ConnectionStrings["YourConnectionString"].ConnectionString;
var conn = new SqlConnection(connectionString);
var comm = new SqlCommand("YourStoredProc", conn) { CommandType = CommandType.StoredProcedure };
try
{
conn.Open();
// Create variables to match up with session variables
var CloseSchoolID = Session["sessCloseSchoolID"];
// SqlParameter for each parameter in the stored procedure YourStoredProc
var prmClosedDate = new SqlParameter("#prmClosedDate", closedDate);
var prmSchoolID = new SqlParameter("#prmSchoolID", CloseSchoolID);
// Pass the param values to YourStoredProc
comm.Parameters.Add(prmClosedDate);
comm.Parameters.Add(prmSchoolID);
comm.ExecuteNonQuery();
}
catch (SqlException sqlex)
{
}
finally
{
conn.Close();
}
If using SQL Server:
SqlConnection connection = new SqlCOnnection("Data Source=yourserver;Initial Catalog=yourdb;user id=youruser;passowrd=yourpassword");
SqlCommand cmd = new SqlCommand("StoredProcName", connection);
cmd.CommandType=StoredProcedureType.Command;
connection.Open();
cmd.ExecuteNonQuery();
connection.Close();
If not then replace Sql with Ole and change the connection string.
Here is a good starting point http://support.microsoft.com/kb/310130
OdbcConnection cn;
OdbcCommand cmd;
OdbcParameter prm;
OdbcDataReader dr;
try {
//Change the connection string to use your SQL Server.
cn = new OdbcConnection("Driver={SQL Server};Server=servername;Database=Northwind;Trusted_Connection=Yes");
//Use ODBC call syntax.
cmd = new OdbcCommand("{call CustOrderHist (?)}", cn);
prm = cmd.Parameters.Add("#CustomerID", OdbcType.Char, 5);
prm.Value = "ALFKI";
cn.Open();
dr = cmd.ExecuteReader();
//List each product.
while (dr.Read())
Console.WriteLine(dr.GetString(0));
//Clean up.
dr.Close();
cn.Close();
}
catch (OdbcException o) {
MessageBox.Show(o.Message.ToString());
}