Defining Command,commandtype And Connectionstring For SELECT Command Is Not Similar To INSERT And UPDATE
Feb 23, 2007
i am using visual web developer 2005 and SQL 2005 with VB as the code behind
i am using INSERT command like this
Dim test As New SqlDataSource()
test.ConnectionString = ConfigurationManager.ConnectionStrings("DatabaseConnectionString1").ToString()
test.InsertCommandType = SqlDataSourceCommandType.Text
test.InsertCommand = "INSERT INTO try (roll,name, age, email) VALUES (@roll,@name, @age, @email) "
test.InsertParameters.Add("roll", TextBox1.Text)
test.InsertParameters.Add("name", TextBox2.Text)
test.InsertParameters.Add("age", TextBox3.Text)
test.InsertParameters.Add("email", TextBox4.Text)
test.Insert()
i am using UPDATE command like this
Dim test As New SqlDataSource()
test.ConnectionString = ConfigurationManager.ConnectionStrings("DatabaseConnectionString").ToString()
test.UpdateCommandType = SqlDataSourceCommandType.Text
test.UpdateCommand = "UPDATE try SET name = '" + myname + "' , age = '" + myage + "' , email = '" + myemail + "' WHERE roll 123 "
test.Update()
but i have to use the SELECT command like this which is completely different from INSERT and UPDATE commands
Dim tblData As New Data.DataTable()
Dim conn As New Data.SqlClient.SqlConnection("Data Source=.SQLEXPRESS;AttachDbFilename=|DataDirectory|Database.mdf;Integrated Security=True;User Instance=True")
Dim Command As New Data.SqlClient.SqlCommand("SELECT * FROM try WHERE age = '100' ", conn)
Dim da As New Data.SqlClient.SqlDataAdapter(Command)
da.Fill(tblData)
conn.Close()
TextBox4.Text = tblData.Rows(1).Item("name").ToString()
TextBox5.Text = tblData.Rows(1).Item("age").ToString()
TextBox6.Text = tblData.Rows(1).Item("email").ToString()
for INSERT and UPDATE commands defining the command,commandtype and connectionstring is same
but for the SELECT command it is completely different. why ?
can i define the command,commandtype and connectionstring for SELECT command similar to INSERT and UPDATE ?
if its possible how to do ?
please help me
I did a successful Insert to a SQL Server today in .NET VS2005. But before I insert I figure I better make sure the part does not allready exist in the table. Can a check the command to determine if it has a boolan value of False and if so to INSERT as before? Dim myCommand As New SqlClient.SqlCommand
myCommand.CommandText = "Select PartNumber From Pricing Where PartNumber = '" & var0 & "'"
I'm trying to populate a DropDownList from my SQL database. I'm using C# 2005 and when I compile my code I get an error. Compiler Error Message: CS0103: The name 'myConnection' does not exist in the current context using System; using System.Data; using System.Data.SqlClient; using System.Configuration; using System.Collections; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; public partial class Default3 : System.Web.UI.Page { private string connectionString = WebConfigurationManager.ConnectionStrings["mewconsultingConnectionString"].ConnectionString;
protected void Page_Load(object sender, EventArgs e) { SqlCommand myCommand = new SqlCommand(); myCommand.Connection = myConnection; myCommand.CommandText = "SELECT * FROM tblPau"; myConnection.Open(); SqlDataReader myReader; myReader = myCommand.ExecuteReader(); myReader.Read(); // The first row in the result set is now available. lstPau.Items.Add(myReader["PauSiteName"]); myReader.Close(); myConnection.Close(); } }
If i am using SqlCommand Class and the CommandType of it is Text, then will it add "sp_executesql N" in front of the sql command automatically in fact, just like SqlDataAdapter?
I need to move various records from a production database to an archive database. The fields in the two databases are identical but the archive database has an additional "Transfer Date" field. Can anyone recommend an easy way to create an SQL statement to move the record from production to archive? I've tried
INSERT INTO ARCHIVE (SELECT * FROM PRODUCTION WHERE ACCOUNTNO='XYZ')
but I get an error saying the columns among the two tables do not match (obviously because of the "Transfer Date" column). Is there a way to use a similar SQL statement that will populate the "Transfer Date" column w/ today's date?
I have a table with a column called SortOrder. It's an integer. The table also has a name and a city.I want to do an Insert and fill in SortOrder with the next higher integer, of all rows with city='NY'
Insert (name,city,SortOrder) values ('Dave','NY', select max(SortOrder)+1 from myTable where city='NY')
I have created a dataset in code with a select command being a stored procedure. I have used commandbuilder so as to create update, insert statements. The update of the dataset receives error "update requires valid insert command".
From reading, it seems the problem is that the select statement is a stored procedure so data adapter cannot created the insert, update commands.
Can I create an update and insert command using update and insert stored procedures and use those to update the dataset (with multiple records of course) or do I have to create my select command using a select statement rather than the stored procedure?
Hi all, I have a table with the list of tables I need to drop. So basically before droping those tables I need to disable the FK and PK constraints. So I want to spool out the out of this script. SELECT 'ALTER TABLE ' + QUOTENAME( c.TABLE_NAME ) + ' NOCHECK CONSTRAINT ' + QUOTENAME( c.CONSTRAINT_NAME ) AS ALTER_SCRIPT FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS AS c WHERE CONSTRAINT_TYPE = 'FOREIGN KEY'
Is there a way to store the output of this script in a .sql file so that I could execute it. Any thoughts will help! Thank you!
I'm getting duplicate records for the last record in the datatable. No matter how much or how little my datatable contains row records, it always duplicate the last one for some reason. Is there something wrong with my code below? EXAMID pulling from another stored procedure, which is outputed back to a variable. ---Data Access Layer---- If dt.Rows.Count > 0 Then 'INSERT EXAM ROSTERInsertComm = New SqlCommandsqladapter = New SqlDataAdapterInsertComm = New SqlClient.SqlCommand("ExamOfficers_AddOfficerSpecificExamRoster", conndb)InsertComm.CommandType = CommandType.StoredProcedure sqladapter.InsertCommand = InsertCommInsertComm.Parameters.Add("@examid", SqlDbType.Int)InsertComm.Parameters("@examid").Value = examidInsertComm.Parameters.Add("@officerid", SqlDbType.Int, 12, "Officer_UID")InsertComm.Parameters.Add("@reimburse", SqlDbType.Bit, 12, "ReimburseToDb")InsertComm.Parameters.Add("@posttest", SqlDbType.Int, 12, "Post_Test")InsertComm.Parameters.Add("@pqcdate", SqlDbType.DateTime, 12, "pqc_date")InsertComm.Parameters.Add("@pqcscore", SqlDbType.Int, 12, "pqc_score") conndb.Open() sqladapter.UpdateBatchSize = 100InsertComm.UpdatedRowSource = UpdateRowSource.Nonesqladapter.Update(dt) InsertComm.ExecuteNonQuery()InsertComm.Dispose() End If ----Stored Procedure---- ALTER PROCEDURE [dbo].[ExamOfficers_AddOfficerSpecificExamRoster] @ExamID as int,@OfficerID as int,@reimburse as bit=NULL,@posttest as int=NULL,@pqcdate as datetime=NULL,@pqcscore as int=NULL ASBEGIN SET NOCOUNT ON; Insert Into Exam_Officers(EXAM_UID,Officer_UID,reimburse,post_test,pqc_date,pqc_score)values(@ExamID,@OfficerID,@reimburse,@posttest,@pqcdate,@pqcscore) END
i've read the transact-sql command, i known that the select command use to retrieve many fields from many tables with one command select * from table1,table2 yes, but i ' ve not seen the way to add,delete or update those fields from those tables with one command...
Is it possible? why? I don't have any idea , can u help me I want to know the sql commands , if it's possible
How I can get the desired result using query. I don't want any
'@' variable in the result. DECLARE @ST AS varchar(10)='AA' DECLARE @desc AS int=8 DECLARE @STID AS int=4 DECLARE @PP AS int=63 DECLARE @SS AS int=22 /* Desired Result */ Update #RT Set ST='AA', desc=8, STID=4 Where PP=63 and SS=22
i am using a OLE DB Source in my dataflow component and want to select rows from the source based on the Name I enter during execution time. I have created two variables,
enterName - String packageLevel (will store the name I enter)
myVar - String packageLevel. (to store the query)
I am assigning this query to the myVar variable, "Select * from db.Users where (UsrName = " + @[User::enterName] + " )"
Now in the OLE Db source, I have selected as Sql Command from Variable, and I am getting the variable, enterName,. I select that and when I click on OK am getting this error.
Error at Data Flow Task [OLE DB Source [1]]: An OLE DB error has occurred. Error code: 0x80040E0C. An OLE DB record is available. Source: "Microsoft SQL Native Client" Hresult: 0x80040E0C Description: "Command text was not set for the command object.".
Can Someone guide me whr am going wrong?
myVar variable, i have set the ExecuteAsExpression Property to true too.
Hi. I am writing a program in C# to migrate data from a Foxpro database to an SQL Server 2005 Express database. The package is being created programmatically. I am creating a separate data flow for each Foxpro table. It seems to be doing it ok but I am getting the following error message at the package validation stage:
Description: An OLE DB Error has occured. Error code: 0x80040E0C.
An OLE DB record is available. Source: "Microsoft SQL Native Client" Hresult: 0x80040E0C Description: "Command text was not set for the command object".
.........
Description: "component "OLE DB Destination" (22)" failed validation and returned validation status "VS_ISBROKEN".
This is the first time I am writing such code and I there must be something I am not doing correct but can't seem to figure it out. Any help will be highly appreciated. My code is as below:
private bool BuildPackage()
{
// Create the package object
oPackage = new Package();
// Create connections for the Foxpro and SQL Server data
MessageBox.Show("The DTS package was not built successfully because of the following error(s):" + sErrorMessage, "Package Builder", MessageBoxButtons.OK, MessageBoxIcon.Information);
On my site users can register using ASP Membership Create user Wizard control. I am also using the wizard control to design a simple question and answer form that logged in users have access to. it has 2 questions including a text box for Q1 and dropdown list for Q2. I have a table in my database called "Players" which has 3 Columns UserId Primary Key of type Unique Identifyer PlayerName Type String PlayerGenre Type Sting
On completing the wizard and clicking the finish button, I want the data to be inserted into the SQl express Players table. I am having problems getting this to work and keep getting exceptions. Be very helpful if somebody could check the code and advise where the problem is??
To match the answers to the user I get the UserId and insert this into the database to.protected void Wizard1_FinishButtonClick(object sender, WizardNavigationEventArgs e) { SqlDataSource DataSource = (SqlDataSource)Wizard1.FindControl("InsertArtist1"); MembershipUser myUser = Membership.GetUser(this.User.Identity.Name); Guid UserId = (Guid)myUser.ProviderUserKey;String Gender = ((DropDownList)Wizard1.FindControl("PlayerGenre")).SelectedValue; DataSource.InsertParameters.Add("UserId", UserId.ToString());DataSource.InsertParameters.Add("PlayerGenre", Gender.ToString()); DataSource.Insert();
I have a database on a server that im trying to update using asp.net. I tested this on another server and everything worked perfectly. The test system was set up where the website is hosted. But the live system is placed on a different server than the webpage. Does that make a difference? Test System Client -> Website/database Live System: Client -> website -> database I created a user account to use when accessing the database on the live system because i read the double hop causes problems. By using that account i can access and view the data. But whenever i update it nothing happens. NO ERROR either. It works perfectly but does nothing. Anyone have any ideas please?!?!?!
Hi all, just need a LITTLE help here. I am very close, I know I am, but just can't seem to fit the last piece in on this. I have a page that shows current data for a customer and allows you to make changes to the data, then I have a button to push to update the system. If I hard-code in a value in place of '@Pf_Value' it will update that value, so I know my where is working, just SOMETHING missing in syntax on the set statement or something wrong on my cmd.parameters statement. Any help would be great!!Protected Sub UpdateButton_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles UpdateButton.Click Dim sql As String = "update CustomerPOFlexField set [Pf_Value] = @Pf_Value where Pf_property = 'Attrib1' and Pf_CustomerNo = @CustomerNo"Dim newc As String = NewCustomer.Text Using conn As New SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings("HCISDataConnectionString").ConnectionString)Dim cmd As New SqlCommand(sql, conn) cmd.Parameters.AddWithValue("@CustomerNo", DropDownlist1.SelectedValue)cmd.Parameters.Add(New SqlParameter("@Pf_Value", TextBox2.Text)) conn.Open() cmd.ExecuteNonQuery() End Using End Sub Thanks, Randy
Hi all, Im working in VB web application.Im having some values in some textbox and trying to update it using update command and its not working for me... I used ExecuteNonQuery statement after that. The alert message after that is working for me. But the values i changed in textbox in not updating in my database. What could be wrong? cid = lbcid.Text cname = txtname.Text contactname = txtconame.Text tele = Val(txttele.Text) mob = Val(txtmob.Text) email = txtemail.Text genmess = txtgen.Text cmd = New SqlCommand("Update CompanyDetails set CompanyName='" & cname & "',ContactName='" & contactname & "',Telephone=" & tele & ",Mobile=" & mob & ",Generalmess='" & genmess & "',Email='" & email & "'where CompanyId= '" & cid & "'", con)
I'm using SQL Server Management Studio to do an extremely simple table update (I thought). I wish to fill a newly added table field with a value, however I didn't do this before... What I do is:
Hello!I have problems with my SQL insert command..string zdroj = "server=LIBRA; database=ufd; uid=sa; password=555; ";string dotaz = "SELECT heslo FROM tbl_UFD_Uzivatelia WHERE meno='"+meno.Text+"'";SqlConnection conn = new SqlConnection(zdroj);SqlCommand sqlCmd = new SqlCommand(dotaz, conn);conn.Open(); SqlDataReader reader; reader = sqlCmd.ExecuteReader();reader.Read();Does something exist as oposite of DataReader? How can I execute insert command?Hope you will help me, thanx a lot
Hi guys! I have an INSERT INTO sqlcommand that inserts values into a table from another table. Why do I always get this error? Violation of PRIMARY KEY constraint 'PK_TE_shounin_zangyou'. Cannot insert duplicate key in object 'dbo.TE_shounin_zangyou'.The statement has been terminated. Here's the insert command... Dim update_phase As New SqlCommand("INSERT INTO TE_shounin_zangyou (syain_No,date_kyou,time_kyou) SELECT syain_No,date_kyou,time_kyou FROM TE_zangyou WHERE [syain_No] = @syain_No", cnn) The table where I would want to insert data is empty, but I get this error. What seems to be the problem? Thanks. Audrey
i want to include an insert command to enable admin user to insert new record through the grid view but for some reason the insert command doesnt work, and i want the page to just display the record of the restaurant name "Sakura Yeshi" but i cannot do that and i dont know why? Can somebody help me out with this? i know this might be easy but just i dont know how to deal with it. Thanks My Code:<script runat="server"> Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Dim resmen As String Dim connection As SqlConnection = New SqlConnection() connection.ConnectionString = ConfigurationManager.ConnectionStrings("ConnectionString").ToString() resmen = ("SELECT resname,menu,price,date FROM rest_info WHERE resname = 'sakura yeshi'") Dim myCommand As SqlCommand = New SqlCommand(resmen, connection) connection.Open() Dim dr As SqlDataReader = myCommand.ExecuteReader() While dr.Read() admingrid.DataBind() End While connection.Close() End Sub</script> <asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server"> <strong>Sakura Yeshi Admin Page<br /> <asp:GridView ID="admingrid" runat="server" AutoGenerateColumns="False" CaptionAlign="Left" DataSourceID="SqlDataSource1" Style="z-index: 100; left: 163px; position: absolute; top: 182px"> <Columns> <asp:CommandField ShowdeleteButton="True" ShowEditButton ="True" ShowinsertButton="True" /> <asp:BoundField DataField="resname" HeaderText="resname" ReadOnly="True" SortExpression="resname" /> <asp:BoundField DataField="menu" HeaderText="menu" SortExpression="menu" /> <asp:BoundField DataField="price" HeaderText="price" SortExpression="price" /> <asp:BoundField DataField="date" HeaderText="date" SortExpression="date" /> </Columns> </asp:GridView> <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString %>" SelectCommand="SELECT [resname], [menu], [price], [date] FROM [rest_info]" DeleteCommand="DELETE FROM [rest_info] WHERE [resname] = 'sakura yeshi'" InsertCommand="INSERT INTO [rest_info] ([resname], [menu], [price], [date]) VALUES (@resname, @menu, @date, @price)" UpdateCommand="UPDATE [rest_info] SET [resname] = @resname, [menu] = @menu, [price] = @price, [date] = @date WHERE [resname] = 'sakura yeshi'"> <InsertParameters> <asp:Parameter Name="resname" Type="Char" /> <asp:Parameter Name="menu" Type="char" /> <asp:Parameter Name="price" Type="Decimal" /> <asp:Parameter Name="date" Type="datetime" /> </InsertParameters> <UpdateParameters> <asp:Parameter Name="resname" Type="Char" /> <asp:Parameter Name="menu" Type="char" /> <asp:Parameter Name="price" Type="Decimal" /> <asp:Parameter Name="date" Type="datetime" /> </UpdateParameters> <DeleteParameters> <asp:Parameter Name="resname" Type="String" /> </DeleteParameters></asp:SqlDataSource></asp:Content>
Hi, I am creating a page which has 5 text boxes. Firstname, lastname, pass, zip, email and a command button. now when i click this button i want it to use a stored procedure and insert the values from the text box to db table. i dont know what code to put in the command button.
I have three tables t1, t2, t3. I want to insert a new row in t1. I am using access 2000 with sql commands for the queries. There are 4 colums in t1. I know the values of two of the colums. The remaining two columns values are going to be look up in the other 2 tables, 1 value from t2 table and the other value from t3.. I need this to be in one statement. From what I have seen you can either use insert with values() or you can populate your table with unkown values from another table. But I want to do both, since 2 of my values are known and the other 2 need to come from another table.
I hope that I made it clear enough. Can anyone help me
i am completely new to sql commands so i really need the help on this one.
I have three tables and they go like this
--User Table
firstTable->integerID
firstTable->stringName
--Group Table
secondTable->integerID
secondTable->stringName
--User to Groups table
thirdTable->integerFirstID
thirdTable->integerSecondID
thirdTable->stringDescription
the first table is has a user id and name and the second table has a group id and name, the third table keeps track of how many groups the user is assigned to. The problem i am having is writing a sql insert into command to add more entries to the third table from an asp.net 2.0 page, my sql command is incorrect.
The problem i am having i think, is that i am populating a dropdownlist with the names of all of the groups and when i select one that should be the group i am assigning to the user, the problem is, is that i dont know how to associated that dropdownlist string's name with its ID so that it can be passed to my insert command. is there a way to accomplish this all as a sql command? because i have a formview with a multiview and then a gridview under nested under all of that, and it would be a pain to write a event to work with all of the that.
if i do this it works
INSERT INTO ThirdTable (UserID,GroupID,Description) VALUES '318', '2', 'some description')
UPDATE #TempTableESR SET CTRLBudEng = (SELECT SUM(Salaries) from ProjectBudget WHERE Project = @Project)UPDATE #TempTableESR SET CTRLBudTravel = (SELECT SUM(Travels) from ProjectBudget WHERE Project = @Project)UPDATE #TempTableESR SET CTRLBudMaterials = (SELECT SUM(Materials) from ProjectBudget WHERE Project = @Project)UPDATE #TempTableESR SET CTRLBudOther = (SELECT SUM(Others) from ProjectBudget WHERE Project = @Project)UPDATE #TempTableESR SET CTRLBudContingency = (SELECT SUM(Contingency) from ProjectBudget WHERE Project = @Project)above is the UPDATE command i am using in one of my stored procedures. I have to SELECT from my ProjectBudget table 5 times to update my #TempTableESR table. is there an UPDATE command i can use which would let me update multiple fields in a table using one SELECT command?
Im looking for example code to make a sql update... I want to use command.Parameters and variables from text boxes and i'm unsure how to do this... Please help. This code below doesn't work but it is an example of what i've been working with.. <code> { string conn = string.Empty; ConnectionStringsSection connectionStringsSection = WebConfigurationManager.GetSection("connectionStrings") as ConnectionStringsSection; if (connectionStringsSection != null) { ConnectionStringSettingsCollection connectStrings = connectionStringsSection.ConnectionStrings; ConnectionStringSettings connString = connectStrings["whowantsConnectionString"]; conn = connString.ConnectionString; using (SqlConnection connection = new SqlConnection(conn)) using (SqlCommand command = new SqlCommand("UPDATE users SET currentscore=5)", connection)) { updateCommand.Parameters.Add("@currentscore", SQLServerDbType.numeric, 18, "currentscore"); connection.Open(); command.ExecuteNonQuery(); connection.Close(); } } }</code>
i am using visual web developer 2005 and SQL Express 2005 and VB as the code behindi have a table called orderdetail and i want to update the fromdesignstatus field from 0 to 1 in one of the rows containing order_id = 2so i am using the following coding in button click event Protected Sub updatebutton_Click(ByVal sender As Object, ByVal e As System.EventArgs) Dim update As New SqlDataSource() update.ConnectionString = ConfigurationManager.ConnectionStrings("DatabaseConnectionString").ToString() update.UpdateCommandType = SqlDataSourceCommandType.Text update.UpdateCommand = "UPDATE orderdetail SET fromdesignstatus = '1' WHERE order_id = '2'" End Sub but the field is not updatedi do not know where i have gone wrong in my coding. i am sure that my database connection string is correctplease help me
Here I have the following command Dim dtNow As DateTime = DateTime.NowSqlDataSource1.UpdateCommand="Update [db] Set [LW]='TRUE', LWD=dtnow Where [PK]=@PK"What I was ttrying to accomplish was , in my grid view, when someone clicks update, it would automatically set LW to true and set LWD to today's date. No user intervention required. However, I figured the above script would not work. What would I have to do to make LWD = dtnow? I do not want to give the user the option to update anything.
Hello, I'm using a Gridview to display a list of servers. Each server has a column in a table called "Enabled." I want to create a button that is supposed to toggle the value called "Enabled." I am able to make the button either to set Enabled to true or false, but I don't know how to make it toggle. Here is the command:UpdateCommand="UPDATE [ServerStatus] SET [Enabled] = 1 WHERE [ServerName] = @ServerName" The button is a buttonfield in the gridview:<asp:ButtonField ButtonType="Button" CommandName="Update" HeaderText="Toggle" ShowHeader="True" Text="Toggle" /> Does anyone know the syntax, or a way to make the button set Enabled to true when it is false, and false when it is set to true?