I think I'm missing an 'USING" statement in my class as I'm getting an error when I try to set the commandType to stored procedure. When I type 'cmd.CommandType =', Intellisense fails to find the 'CommandType.StoredProcedure (Note: the function is only partly roughed out). Thanks in advance!
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
using System.Data.SqlClient;
namespace LegacyForms.Personal
{
public partial class FormBuilder : System.Web.UI.Page
{
protected void btnSubmit_Click(object sender, EventArgs e)
{
//Get the DB connection:
string ConnString = ConfigurationManager.AppSettings["AssociatedBank2011ConnectionString"];
SqlConnection conn = new SqlConnection(ConnString);
SqlCommand cmd = new SqlCommand("uspInsertPersonalAccountApplcation", conn);
cmd.Commandtype = **get error here!**
cmd.Parameters.AddWithValue("#AccountType", AcctType);
cmd.Parameters.AddWithValue("#AccountSubType", AcctSubType);
cmd.Parameters.AddWithValue("#CheckingOption", CheckOption);
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
}
}
}
using System.Data;
You need to reference System.Data. See the MSDN Reference for the CommandType Enumeration. Direct quote:
Namespace: System.Data
Assembly: System.Data (in System.Data.dll)
I'd also recommend the other using statement for your SqlConnection and SqlCommand objects. Since they both implement the IDisposable interface, you can do the following:
string ConnString = ConfigurationManager.AppSettings["AssociatedBank2011ConnectionString"];
using (SqlConnection conn = new SqlConnection(ConnString))
using (SqlCommand cmd = new SqlCommand("uspInsertPersonalAccountApplcation", conn))
{
cmd.Commandtype = CommandType.StoreProcedure;
cmd.Parameters.AddWithValue("#AccountType", AcctType);
cmd.Parameters.AddWithValue("#AccountSubType", AcctSubType);
cmd.Parameters.AddWithValue("#CheckingOption", CheckOption);
conn.Open();
cmd.ExecuteNonQuery();
}
That way, in the case that your code works correctly or throws an exception in the using block, your SqlConnection and SqlCommand will clean up after themselves.
In such situations you can press CTRL + . (ctrl + dot) to get a suggestion like do you want to add using System.Data...
P.S. Teach a men to fish ...
Related
I am trying to simply insert values into an SQL table. The ID in the database cannot be AUTO_INCREMENT so I use MAX and +1. Not only will this code not make a new ID, it simply isn't inserting anything into the table.
Even in the debugger there are no errors or warnings, it just isn't showing up in the database itself..
Here is my code:
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Windows;
using System.ComponentModel;
using System.Drawing;
using System.Text;
namespace WebApplication2
{
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void ButtonClick(object sender, EventArgs e){
using (var sqlConnection1 = new SqlConnection("Data
Source=SERVER; Initial Catalog = Metal; Integrated
Security = True"))
{
SqlDataAdapter cmd = new SqlDataAdapter();
using (var insertData = new SqlCommand("INSERT INTO ApptIn
(CONTROLNUMBER, CARRIERNAME, EXPECTEDNUMOFPIECES, EXPECTEDWEIGHT) VALUES
(#carrierSelectInput,
#pieceCountInput, #weightinput)")
{
SqlCommand generateApptNum = new SqlCommand();
View appNumView = new View();
insertData.Connection = sqlConnection1;
string carrierSelectInput = DropDownList1.Text;
string pieceCountInput = TextBox1.Text;
string weightInput = TextBox2.Text;
insertData.Parameters.Add("#carrierSelectInput",
carrierSelectInput.VarChar);
insertData.Parameters.Add("#pieceCountInput",
pieceCountInput.Int);
insertData.Parameters.Add("#weightInput",
weightInput.Int);
cmd.InsertCommand = insertData;
sqlConnection1.Open();
insertData.ExecuteNonQuery();
generateApptNum.ExecuteNonQuery();
sqlConnection1.Close();
}
}
}
}
}
EDIT: I have tried running the SQL into the DB and it gave an error, so I changed it(updated in code) but it puts in at ID=0...
I know you have already committed to your plan, but, I feel that I have to point out that, due to the sub select for the Max id value in your query, the insert statement has the potential to be much slower than a normal insert.
If you are planning on inserting a large number of rows or creating an API for use throughout the code I highly recommend either adjusting the column definition to be an identity column or to consider using a a sequence to generate the ids.
The issue could be that you need to specify the CommandType to be CommandType.Text on the insertData command. There is a lot going on in the original code with multiple sqlcommands being declared. I think the code could be simplified as such:
protected void ButtonClick(object sender, EventArgs e)
{
using (var sqlConnection1 = new SqlConnection("data source=testServer;initial catalog=testCat;integrated security=True;"))
using (var insertData = new SqlCommand("insert into tempExample (id, code, description) values ((select max(coalesce(id, 1)) from tempExample)+1, #code, #description)", sqlConnection1))
{
insertData.CommandType = CommandType.Text;
insertData.Parameters.AddWithValue("#code", "Testing4");
insertData.Parameters.AddWithValue("#description", "Testing3");
sqlConnection1.Open();
insertData.ExecuteNonQuery();
sqlConnection1.Close();
}
}
Update - I changed the code above to reflect a working test on my local machine. Note that the connection string format is different (lack of spaces).
I am trying to write myself a Music record database program.
It works perfectly untill I try using a form to add data using input from textboxes and a button.
It generates a break point and the following error
An Unhandled exception of type 'System.ArgumentException' Occured in
System.Data.dll
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace Musicrecord
{
public partial class Form3 : Form
{
public Form3()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
--> using(var connection = new SqlConnection("connectionString"))**
{
connection.Open();
var sql = "INSERT INTO Table(Artist, Album, Release Year) VALUES(#Artist, #Album, #Release year)";
using(var cmd = new SqlCommand(sql, connection))
{
cmd.Parameters.AddWithValue("#Artist", textBox1.Text);
cmd.Parameters.AddWithValue("#Album", textBox2.Text);
cmd.Parameters.AddWithValue("#Release Year ", textBox3.Text);
cmd.ExecuteNonQuery();
}
I haven't found after several hours of googling a solution.
If connectionString is a local variable, you need to use it as;
using(var connection = new SqlConnection(connectionString))
not
using(var connection = new SqlConnection("connectionString"))
If you use it as "connectionString", SqlConnection expects it is a valid connection string. But it is not.
Also, if your column name more than one word, you need to use it with square brackets like [Release Year]. It is the same as it's paramter name.
And don't use AddWithValue. It may generate unexpected results. Use .Add() method or it's overloads.
using(var connection = new SqlConnection(connectionString))
using(var cmd = connection.CreateCommand())
{
cmd.CommandText = "INSERT INTO Table(Artist, Album, [Release Year]) VALUES(#Artist, #Album, #ReleaseYear)";
cmd.Parameters.Add(#Artist, SqlDbType.NVarChar).Value = textBox1.Text;
cmd.Parameters.Add(#Album, SqlDbType.NVarChar).Value = textBox2.Text;
cmd.Parameters.Add(#ReleaseYear, SqlDbType.NVarChar).Value = textBox3.Text;
connection.Open();
cmd.ExecuteNonQuery();
}
I assumed your all data types are NVarChar. Also it is a good practice to specify size value as a third parameter in .Add() method.
What is wrong with my code? When Im setting up the connection between my sql and asp, it gives me this error : the sqlcommand cannot be found. Are you missing...."
Here is my code.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.Sql;
protected void Button2_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["Connection"].ConnectionString);
SqlCommand cmd = new SqlCommand("Insert into CarTab( Brand,Model,Plate,Color,Service) Values (#brand,#model,#plate,#color,#year,#service)",conn);
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#brand", Label1.Text);
cmd.Parameters.AddWithValue("#model", Label2.Text);
cmd.Parameters.AddWithValue("#plate", Label3.Text);
cmd.Parameters.AddWithValue("#color", Label4.Text);
cmd.Parameters.AddWithValue("#year", Label5.Text);
cmd.Parameters.AddWithValue("#service", Label6.Text);
conn.Open();
cmd.ExecuteNonQuery();
}
I've already put Using system.data; and Using system.data.sql; but it still the same.
Error :
1.The type or namespace name 'SqlConnection' could not be found (are you missing a using directive or an assembly reference?)
2.The type or namespace name 'SqlConnection' could not be found (are you missing a using directive or an assembly reference?)
3.The name 'ConfigurationManager' does not exist in the current context
4.The type or namespace name 'SqlCommand' could not be found (are you missing a using directive or an assembly reference?)
5.The type or namespace name 'SqlCommand' could not be found (are you missing a using directive or an assembly reference?)
Hope this help you in finding solution for my errors. Thanks
Two things. You haven't closed your SQL command:
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["Connection"].ConnectionString);
SqlCommand cmd = new SqlCommand("Insert into CarTab")
And secondly, you don't have any qualifying data to insert in to your CarTab table? You need to specify the fields and values:
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["Connection"].ConnectionString);
SqlCommand cmd = new SqlCommand("Insert into CarTab(field1, field2) VALUES('val1', 12)")
There are a number of other ways to insert data - like the INSERT SELECT:
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["Connection"].ConnectionString);
SqlCommand cmd = new SqlCommand("Insert into CarTab(field1, field2) SELECT field1, field2 FROM Table2")
http://www.sqlteam.com/article/using-select-to-insert-records
Further to the comments, here is an example of how to fully use ADO in the way you have specified:
using System.Data;
using System.Data.SqlClient;
using (var con = new SqlConnection("your connection string")) {
con.Open();
using (var com = con.CreateCommand()) {
var var1 = "test";
var var2 = "test2";
com.CommandText = string.Format("INSERT INTO Table1(col1, col2) VALUES({0}, {1})", var1, var2);
com.CommandType = CommandType.Text;
com.ExecuteNonQuery();
}
con.Close();
}
Please note that I haven't tested it, but it should give you a good starting block.
Have you added reference to System.Data assembly?
1) You have not closed the SqlCommand object and wrong Sql Insert statement.
It would be
SqlCommand cmd = new SqlCommand("Insert into CarTab(col1,col2,...) VALUES(val1,val2,..)");
2) You have not open the connection and not assign a connection to a command object like
conn.Open();
cmd.Connection = conn;
3) and after executing the query you have to close the connection
cmd.ExecuteNonQuery();
conn.Close(); // close the connection.
System.Data.Sql is for SqlServer
http://msdn.microsoft.com/en-us/library/system.data.sql.aspx
The System.Data.Sql namespace contains classes that support SQL
Server-specific functionality.
Use the ADO.NET driver found here: http://www.mysql.com/products/connector/
or use ODBC (not the preferred option).
what kind of db program are you using? since like grayfox said here above you are in need of sql server, and try doing it this way, worked fo rme:
using (SqlConnection connection = new SqlConnection())
{
string connectionStringName = this.DataWorkspace.dbsMSccData.Details.Name;
connection.ConnectionString =
ConfigurationManager.ConnectionStrings[connectionStringName].ConnectionString;
string procedure = entity.Procedure;
using (SqlCommand command = new SqlCommand(procedure, connection))
{
command.CommandType = CommandType.StoredProcedure;
//foreach (var item in entity.StoredProcedureParameters)
//{
// command.Parameters.Add(
// new SqlParameter(item.ParameterName, item.ParameterValue));
//}
connection.Open();
command.ExecuteNonQuery();
}
}
this.Details.DiscardChanges();
My first issue: I am trying to establish connection to MySql database, but I keep getting error when I debug it with Visual Studio:"Connection must be valid and open."
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Threading;
using MySql.Data.MySqlClient;
using MySql.Data.Types;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
MySqlConnection conn;
string myConnectionString;
myConnectionString = "server=localhost;User Id=root;database=test3";
using (conn = new MySqlConnection(myConnectionString))
{
DateTime startTime = DateTime.Now;
MySqlCommand cmd = new MySqlCommand("SELECT * FROM department");
// sleep for 2.5s
Thread.Sleep(2500);
conn.Open();
var reader = cmd.ExecuteReader();
conn.Close();
}
}
}
My second issue: if there a way to display all this on a ASP.NET Web form (I want to leave code on server side), but display data something like ListView or GridView? Thanks in advance
You need to call conn.Open() before using it.
You forgot to attach your connection to the command:
cmd.Connection = conn;
Book_Return_form
Book_tag_id=textbox1
Member_id=textbox2
Book_return_on=textbox3
Book_due_date=textbox4
Fine=textbox5
In this form when I put book-tag_id the rest items come automatically a/c to database and I hv done all till textbox4(book_due_date).
Now problem is with fine(textbox5)
Fine is calculated acc to membership_type,there are three types of membership silver,gold,platinum
Fines are:silver=30,gold=20,platinum=30 so the calculated fine a/c membership come on text box
As (return_date-due_date)-30,20or10 ,till now I m working with dataadapter but now I want to work with dll class,I make a dll class and know how to add reference to project but I m missing smthing in my code while I m making class.(so help me in code)
I made a stored procedure with name(member_details)colums:tag_id,member_id,membership_type_id,membership_type(eg:909,5,1,silver)
My full code for dll class is:
Firstly,I make class name transcation_details
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.SqlClient;
namespace selectfinedetails
{
public class TransactionService
{
SqlConnection cs;
private void OpenConnection()
{
cs = new SqlConnection();
cs.ConnectionString = "Data Source=IRIS-CSG-174;Initial Catalog=library_system;Integrated Security=True";
cs.Open();
}
public membership_details calculatefine()
{
OpenConnection();
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "Exec member_fine_detail";
SqlParameter prm1=new SqlParameter("member_id", SqlDbType.Int);
cmd.Parameters.Add(prm1);
SqlParameter prm2=new SqlParameter("fine_per_day", SqlDbType.Int);
cmd.Parameters.Add(prm2);
prm1.Direction=ParameterDirection.Output;
prm2.Direction=ParameterDirection.ReturnValue;
membership_details myObjec = new membership_details();
cmd.ExecuteNonQuery();
SqlDataReader sdr = cmd.ExecuteReader();
myObjec.fine_per_day = //cmd.CommandText;(this is error)
return myObjec;
but I this above code I m missing smthing,as this code will result nthing as to calculate fine with member_id…so what code I will add in it and in as calculatefine()