Can I call a sql command parameter from another class? - c#

I have 14 tables, with the usual sql common command parameters, insert, update etc. Beginners, like me, will have all the methods in the main class, like this...
namespace TestApp
{
public partial class TestNamTxt : Form
{
private OleDbConnection myCon;
public TestNamTxt()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
myCon = new OleDbConnection();
myCon.ConnectionString = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C\:...
Database2.mdb")
myCon.Open();
ds1 = new DataSet();
string sql = "SELECT * FROM Table1";
da = new System.Data.OleDb.OleDbDataAdapter(sql,myCon);
da.Fill(ds1, "Foo");
myCon.Close();
};
private void Insertbtn_Click(object sender, EventArgs e)
{
OleDbCommand cmd = new OleDbCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "INSERT INTO Table1 (ID, Name)";
cmd.Parameters.AddWithValue("#ID", IDTxt.Text);
cmd.Parameters.AddWithValue("#Name", NameTxt.Text);
cmd.Connection=myCon;
myCon.Open();
cmd.ExecuteNonQuery();
myCon.Close();
}
}
Could I place code the above code in another class and in the Insertbtn method use the this method? Is there any tutorials or perhaps someone could demonstrate how this could be done? I am not sure what it is called on the description I have given here? Thanks in advance

Sure you can. You can place GetConnection and Insert into separate class(or even leave in Form, but I don't recommend this) and use them as follows:
public static OleDbConnection GetConnection()
{
var myCon = new OleDbConnection();
myCon.ConnectionString = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C\:... Database2.mdb";
return myCon;
}
public static void Insert(string id, string name)
{
var con = GetConnection();
OleDbCommand cmd = new OleDbCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "INSERT INTO Table1 (ID, Name)";
cmd.Parameters.AddWithValue("#ID", id);
cmd.Parameters.AddWithValue("#Name", name);
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
private void Insertbtn_Click(object sender, EventArgs e)
{
Insert(IDTxt.Text, NameTxt.Text);
}
You can also specify Table name as method parameter if you need.

If i have understood your question correctly
then ya you can do this.
Basically you are trying to use DAL(Data Access Layer) the term used for this,
well its simple,
place the above code into another class and then make an object of that class in this class and use it.
public class DataClass
{
public static bool AddEmp(string id, string name)
{
bool result;
OleDbCommand cmd = new OleDbCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "INSERT INTO Table1 (ID, Name)";
cmd.Parameters.AddWithValue("#ID", id);
cmd.Parameters.AddWithValue("#name", name);
cmd.Connection=myCon;
try
{
myCon.Open();
cmd.ExecuteNonQuery();
result = true;
}
catch
{
result = false;
}
myCon.Close();
return result;
}
and then in the insert function do it like this
private void Insertbtn_Click(object sender, EventArgs e)
{
DataClass ob = new DataClass();
bool returnResult = ob.AddEmp(IDtxt.txt, NameTxt.text)
if(bool) // if result == true
//dosomething
else
// do something
}
Hope it helps.

Your TestNam class is derived from the Form class. Any form event handler you want to define must be a member function of TestNam, but within this function you can do what you want, including passing a reference to the active instance of the form.
If your functions are specific to the form class, put them in the class, if they're shared, you can put htem in another object.

Related

How to insert into an identity column in MS SQL

I have the following code:
SqlCommand writeCommand = new SqlCommand("INSERT INTO computers(id)VALUES()", conn.GetConnection());
writeCommand.ExecuteNonQuery();
The table computers contains an INT idientity(1,1) column named id.
When I run the code, I get a System.Data.SqlClient.SqlException: Incorrect syntax near ')'. I've tried to find a solution, but can't find one on the internet.
If the table has other columns as well, and you want to populate them with NULL or their DEFAULT values, then you can use DEFAULT VALUES:
INSERT INTO dbo.computers
DEFAULT VALUES;
If, however, your table only have the one column, then personally using an IDENTITY is the wrong choice; a table that just has an IDENTITY is clearly being misused. Instead, use a SEQUENCE:
CREATE SEQUENCE dbo.Computers START WITH 1 INCREMENT BY 1;
This scales far better, and doesn't suffer the likely race conditions you have. Then, when running an INSERT (or similar) you would use NEXT VALUE FOR dbo.Computers.
For an auto-incrementing identity column the database handles the id value unless I missed something in what you are attempting to do.
public void DemoInsert(string ComputerName, ref int newIdentifier)
{
using (var conn = new SqlConnection { ConnectionString = ConnectionString })
{
using (var cmd = new SqlCommand { Connection = conn })
{
cmd.CommandText = "INSERT INTO computers (ComputerName) " +
"VALUES (#ComputerName); " +
"SELECT CAST(scope_identity() AS int);";
cmd.Parameters.AddWithValue("#ComputerName", ComputerName);
cn.Open();
newIdentifier = (int)cmd.ExecuteScalar();
}
}
}
I have similar code like your app, think about it simple crud app
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
SqlConnection con;
SqlDataAdapter da;
SqlCommand cmd;
DataSet ds;
void fillGrid()
{
con = new SqlConnection("Data Source=.;Initial Catalog=schoolDb;Integrated Security=True");
da = new SqlDataAdapter("Select * from ogrenciler",con);
ds = new DataSet();
con.Open();
da.Fill(ds, "students");
dataGridView1.DataSource = ds.Tables["students"];
con.Close();
}
private void Form1_Load(object sender, EventArgs e)
{
fillGrid();
}
private void Addbtn_Click(object sender, EventArgs e)
{
cmd = new SqlCommand();
con.Open();
cmd.Connection = con;
cmd.CommandText="insert into students(StudentId,StudentName,StudentSurname,City) values("+StudentId.Text+",'"+StudentName.Text+"','"+StudentSurname.Text+"','"+City.Text+"')";
cmd.ExecuteNonQuery();
con.Close();
fillGrid();
}
private void Updatebtn_Click(object sender, EventArgs e)
{
cmd = new SqlCommand();
con.Open();
cmd.Connection = con;
cmd.CommandText = "update Students set ogrenci_ad='"+StudentName.Text+"',StudentName='"+StudentSurname.Text+"',City='"+City.Text+"' where StudentId="+StudentId.Text+"";
cmd.ExecuteNonQuery();
con.Close();
fillGrid();
}
private void Deletebtn_Click(object sender, EventArgs e)
{
cmd = new SqlCommand();
con.Open();
cmd.Connection = con;
cmd.CommandText = "delete from ogrenciler where ogrenci_no="+StudentId.Text+"";
cmd.ExecuteNonQuery();
con.Close();
fillGrid();
}
}
}

Trying to use an INSERT method but not working

i'm trying to use an insert method in my studentHelperClass, I am trying to activate it on a button click on my form, I don't know how to make it work with a text box, so if someone could help with that, that would be great.
This is my method:
public static void insertStudent()
{
MySqlConnection conn = connection();
conn.Open();
MySqlCommand cmd = new MySqlCommand();
cmd.Connection = conn;
string myInsertSQL = "INSERT INTO person(personID) ";
cmd.Prepare();
myInsertSQL += "VALUES (#personID)";
cmd.Parameters.AddWithValue("#personID", "123345667788");
prevID(conn, cmd);
}
and this is my form:
private void btnInsert_Click(object sender, EventArgs e)
{
studentHelperClass.insertStudent();
}
EDIT:
private static void prevID(MySqlConnection conn, MySqlCommand cmd)
{
conn.Open();
cmd.ExecuteNonQuery();
long studentNumber = (long)cmd.LastInsertedId;
Console.Write("previous id {0} ", studentNumber);
Console.ReadLine();
conn.Close();
}
Considering the information, assuming that your prevId(conn,cmd) is calling ExecuteNonQuery, you will still need to set the cmd.CommandText to be equal to your myInsertSql (as other answers have pointed out).
To answer your question though,
private void btnInsert_Click(object sender, EventArgs e)
{
studentHelperClass.insertStudent(studentIdTextBox.Text);
}
public static void insertStudent(string studentId)
{
MySqlConnection conn = connection();
conn.Open();
MySqlCommand cmd = new MySqlCommand();
cmd.Connection = conn;
string myInsertSQL = "INSERT INTO person(personID) ";
cmd.Prepare();
myInsertSQL += "VALUES (?personID)";
cmd.CommandText = myInsertSQL;
cmd.Parameters.AddWithValue("?personID", studentId);
prevID(conn, cmd);
}
Ive also assumed your studentId is a string. If the database has it as a bigint, you will have to do the proper long.TryParse() call.
You need to set cmd.CommandText as myInsertSQL
and also need to call cmd.ExecuteNonQuery()
string sql = "INSERT INTO person (personID) VALUES (#personID)";
using (MySqlConnection conn = connection())
using (MySqlCommand cmd = new SqlCommand(sql, conn))
{
cmd.Parameters.AddWithValue("#personID", personID);
conn.Open();
cmd.ExecuteNonQuery();
}
You must assign your string variable, 'myInsertSQL' to cmd.CommandText, and then call, cmd.ExecuteNonQuery();
I.e.
cmd.CommandText = myInsertSQL;
cmd.ExecuteNonQuery();
cmd.Dispose();
Always call 'Dispose();' when finished so the .net Garbage Collection can cleanup and manage resources.
You don't use the myInsertSQL string at all, you just set it. You have to set the string as the command text by cmd.CommandText = myInsertSQL and you have to call the method cmd.ExecuteNonQuery().

Can't Update with sqlcommand and Parameters

I have some trouble to update my sql server 2005 database when i use parameters.Here you can see the code that normally has to work.I precise that i already make others treatments such as insert into and it worked perfectly.
myCommand.Parameters.AddWithValue("#Pk", this.pk);
myCommand.Parameters.AddWithValue("#Titre", this.titre);
myCommand.CommandText = "Update Action set titre=#Titre where pk=#Pk";
//Execute la commande
myCommand.ExecuteNonQuery();
EDIT:When i use hard code such as:
myCommand.CommandText = "Update Action set titre='title' where pk=#Pk";
it works...
I don't know where you went wrong this is the working code for me
string strCon = #"Data Source=SYSTEM19\SQLEXPRESS;Initial Catalog=TransactionDB;Integrated Security=True";
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
SqlConnection cn = new SqlConnection(strCon);
SqlCommand cmd = new SqlCommand("select * from tblTransaction1", cn);
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd;
DataSet ds = new DataSet();
da.Fill(ds);
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
txtName.Text = ds.Tables[0].Rows[i]["FirstName"].ToString();
txtName1.Text = ds.Tables[0].Rows[i]["LastName"].ToString();
}
}
}
Button click code
protected void btnInsert_Click(object sender, EventArgs e)
{
SqlConnection cn = new SqlConnection(strCon);
obj1.FirstName = txtName.Text;
obj1.LastName = txtName1.Text;
if (obj1.upDate(cn))
{
}
}
Sample class code file
private bool m_flag = false;
private string strFirstName;
private string strLastName;
public string FirstName
{
get { return strFirstName; }
set { strFirstName = value; }
}
public string LastName
{
get { return strLastName; }
set { strLastName = value; }
}
public bool upDate(SqlConnection con)
{
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
if (con.State != ConnectionState.Open)
{
con.Open();
}
try
{
cmd.Parameters.AddWithValue("#Fname", FirstName);
cmd.Parameters.AddWithValue("#Lname", LastName);
cmd.CommandText = "Update tblTransaction1 set LastName=#Lname where FirstName=#Fname";
if (cmd.ExecuteNonQuery() > 0)
{
m_flag = true;
}
}
catch
{
}
return m_flag;
}
Sample Images
I've seen weird results when you forget to include the "CommandType" parameter. Since you using inline SQL, it should be set to "CommandType.Text".
myCommand.Parameters.AddWithValue("#Pk", this.pk);
myCommand.Parameters.AddWithValue("#Titre", this.titre);
myCommand.CommandText = "Update Action set titre=#Titre where pk=#Pk";
// Added CommandType //
myCommand.CommandType = CommandType.Text;
//Execute la commande
myCommand.ExecuteNonQuery();
I have noticed that copying the entire code into a new project helps. I have ran into many times my code would work and then the next day would not, or would only work for someone else and not me. Usually this is due to the designer side of the project when adding and removing code from your project. Just because you delete specific code does not mean the program can update the entire class/project.
If you do :
Int32 rowsAffected = command.ExecuteNonQuery();
Console.WriteLine("RowsAffected: {0}", rowsAffected);
What does it say ?
Try also to prefix your Action table, with the schema name, for example :
myCommand.CommandText = "Update MySchema.Action set titre=#Titre where pk=#Pk";
Because sometimes it can depend on the schema and the user's rights to update this schema.
You could try this: instead of adding the parameters like that
myCommand.Parameters.AddWithValue("#Titre", this.titre);
you should add them with data type.
myCommand.Parameters.Add(new SqlParameter("#Titre", SqlDbType.VarChar, 50));
myCommand.Parameters["#Titre"].Value = this.titre;
That way, the final SQL will be Update Action set titre='titre' instead of Update Action set titre=title. Look that in the second statement titre is not inside quotes ''.
Try adding the parameters after declaring the command.
myCommand.CommandText = "Update Action set titre=#Titre where pk=#Pk";
myCommand.Parameters.AddWithValue("#Pk", this.pk);
myCommand.Parameters.AddWithValue("#Titre", this.titre);
//Execute la commande
myCommand.ExecuteNonQuery();
I found something similar (not identical) here: http://forums.asp.net/t/1249831.aspx/1

Checking condition which table to Insert

I want to Check the "refno" already present in Tbldelivery table, If "refno" is present, then it will insert in "Tbldeliverydetails" because "refno" is primary key in 1st table. Where i check the condition ?
Here is the code i wrote in C# :
protected void btndlysave_Click(object sender, EventArgs e)
{
SqlConnection SqlCon = new SqlConnection("server=(local);Initial Catalog=TestDB;Integrated Security=SSPI;");
try
{
SqlCon.Open();
SqlCommand cmd = new SqlCommand("insert into Tbldelivery (refno,deliverdate,requestby,projectcode) values
(#refno,#deliverdate,#requestby,#projectcode) WHERE not exists (select refno from Tblinkdelivery where refno = #refno)", SqlCon);
cmd.CommandType = CommandType.Text;
if ( need check here)
cmd.Parameters.AddWithValue("#refno", txtdelrefno.Text.Trim());
cmd.Parameters.AddWithValue("#deliverdate", txtdeldate.Text.Trim());
cmd.Parameters.AddWithValue("#requestby", txtdelreq.Text.Trim());
cmd.Parameters.AddWithValue("#projectcode", ddlprojcode.Text.Trim());
}
else
{
SqlCommand cmd2 = new SqlCommand("insert into Tbldeliverdetails (refno,printercode,inkcode,quantity,price,notes) values (#refno,#printercode,#inkcode,#quantity,#price,#notes)", SqlCon);
cmd2.CommandType = CommandType.Text;
cmd2.Parameters.AddWithValue("#refno", txtdelrefno.Text.Trim());
cmd2.Parameters.AddWithValue("#printercode", ddldelprcode.Text.Trim());
cmd2.Parameters.AddWithValue("#inkcode", ddlinkcode.Text.Trim());
cmd2.Parameters.AddWithValue("#quantity", txtdelqty.Text.Trim());
cmd2.Parameters.AddWithValue("#price", txtdelprice.Text.Trim());
cmd2.Parameters.AddWithValue("#notes", txtdelnotes.Text.Trim());
int val1 = cmd.ExecuteNonQuery();
int val2 = cmd2.ExecuteNonQuery();
}
finally
{
SqlCon.Close();
}
}
I think first of all you need to arrange your code.
Writing everything inside the button click event is not good at all. It is better if you can separate business logic and put it separately.
Try something like this.
You can create Data Access class which handle your data access.
In your Data Access Class
public SqlConnection OpenConnection()
{
try
{
var conn = new SqlConnection(“xxx”);
conn.Open();
return conn;
}
catch (Exception ex)
{
//log the exception
return null;
}
}
YourFunction(parameters)
{
var conn = OpenConnection();
if(conn != null)
{
//your code
// you can do something similar as JeremyK explained here
}
}
And in your button click
protected void btndlysave_Click(object sender, EventArgs e)
{
//CHECK THE PARAMETERS AND PASS
//DataAccess. YourFunction(parameters)
}
You query the table and see if it exists.
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
SqlCommand sqlCommand =
new SqlCommand("SELECT * FROM dbo.Tbldelivery WHERE refno=#refno",
connection);
sqlCommand.Parameters.Add("#refno", System.Data.SqlDbType.VarChar);
sqlCommand.Parameters["#refno"].Value = refnoValue;
SqlDataReader reader = sqlCommand.ExecuteReader();
reader.Read();
if (reader.HasRows)
{
// refno exists
}
else
{
// refno does not exist
}
}

Crashing on insert of data into an access database

I am working In c# and inserting my data into an Access database. It runs properly but crashes when I try to insert data, any idea why?
public partial class StudentInfo : Form
{
private OleDbConnection myCon;
public StudentInfo()
{
InitializeComponent();
myCon = new OleDbConnection(#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Documents and Settings\Administrator\My Documents\Visual Studio 2008\Projects\database program\database program\Students.mdb");
}
private void InsertBtn_Click(object sender, EventArgs e)
{
OleDbCommand cmd = new OleDbCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "Insert into StudentInfo(Rollno,SName,SFather,SAdress) Values ('"+ Rollnotb.Text+"','"+nametb.Text+"','"+fathertb.Text+"','"+adresstb.Text+"')";
cmd.Connection=myCon;
myCon.Open();
cmd.ExecuteNonQuery();
myCon.Close();
}
}
The problem can be that you are inserting all fields as text values and maybe some are defined as numeric in the MS Access table (rollNo?)
Also, get used to using paremeters in your queries:
cmd.CommandText = "Insert into StudentInfo(Rollno,SName,SFather,SAdress) Values (?,?,?,?)";
cmd.Parameters.Add(new OleDbParameter("#rollNo", rollNoValue)); //etc.

Categories