Insert Av Value In A Sql-server Database
Nov 10, 2006
Hello:
I have a code that save information from a textbox to a access-database...And it work exactly the way I want....
Now I want to change the database to a sql-server-database....but I dont know what to change in the code I have...
The code for the access-database is:
<% @(a) Page Language="VB" %>
<% @(a) import Namespace="System.Data" %>
<% @(a) import Namespace="System.Data.Oledb" %>
<script runat="server">
sub submit(obj as object, e as eventargs)
Dim MinConnectionString as string = _
"Provider=Microsoft.Jet.Oledb.4.0;" & _
"Data Source=MinDatabas.mdb"
Dim strSQL As String = "INSERT INTO tabell1(namn) VALUES( @(a)Namn)"
Dim Conn As New OledbConnection(MinConnectionString)
Dim Command As New OledbCommand("",Conn)
Command.CommandText = strSQL
Dim Namn As New OledbParameter(" @(a)Namn", DbType.String)
Namn.Value = tbNamn.Text
Command.Parameters.Add(Namn)
Try
Conn.Open()
Command.ExecuteNonQuery()
Conn.Close()
response.redirect("startsida.aspx")
Catch Ex As Exception
lblMessage.text = "Ett fel inträffade"
End try
end sub
</script>
I have been trying to make this code working with a sql-server-database for a very long time now and I think it will be something like this:
<% @(a) Page Language="VB" %>
<% @(a) import Namespace="System.Data" %>
<% @(a) import Namespace="System.Data.sqlclient" %>
<script runat="server">
Sub Spara(ByVal obj As Object, ByVal e As EventArgs)
Dim ConnectionString As String = "Data Source=.SQLEXPRESS;AttachDbFilename=|DataDirectory|MinData
bas.mdf;Integrated Security=True;User Instance=True"
Dim strSQL As String = ("INSERT INTO Tabell1 ( Fornamn ) VALUES ( @(a)Namn )")
Dim Conn As New SqlConnection(ConnectionString)
Dim Command As New SqlCommand("", Conn)
Command.CommandText = strSQL
Dim Namn As New SqlParameter(" @(a)Namn", DbType.String)
Namn.Value = TextBox1.Text
Command.Parameters.Add(Namn)
Try
Conn.Open()
Command.ExecuteNonQuery()
Conn.Close()
Response.Redirect("startsida.aspx")
Catch Ex As Exception
TextBox1.Text = "Ett fel inträffade!"
End Try
End Sub
</script>
But I allways get a message: "Cannot insert the value NULL into column 'id'"
Do you know what's wrong?
View 3 Replies
ADVERTISEMENT
Jul 10, 2001
hi all
just i want to know how to insert image into database. pl help.
thanks
kum
View 2 Replies
View Related
Jun 6, 2006
How to insert date to the sql server database.I am getting input from the HTML form and store it to database usingASP.how to store date field, what datatype needed and what conversionneeded.Thanx & Regards,SSG
View 1 Replies
View Related
Sep 8, 2006
hi,
i want to insert only time in my sql server database.but when m try to insert time in database it takes time+default date. i want to eliminate this default date.
plz any one know this then tell me.
Regards,
shruti.
View 34 Replies
View Related
Feb 25, 2005
Dim con As New SqlConnection(ConfigurationSettings.AppSettings("con"))
con.Open()
Dim info= "this is a des."
Dim fs As New FileStream _
("C:Inetpubwwwrootimages est.jpeg", FileMode.OpenOrCreate, _
FileAccess.Read)
lblInfo.Text = "filestream created"
strInsert = "INSERT INTO image ( image, text ) VALUES ( 'fs' ,'" & info& "');"
lblInfo.Text = "Insert complete"
cmdInsert = New SqlCommand(strInsert, con)
cmdInsert.ExecuteNonQuery()
con.Close()
- Why is'nt the image inserted, only the text / info?
View 1 Replies
View Related
Mar 29, 2005
hi guys
im having real problems and dont know how to solve it at all
i have a web app which allows users to enter information through edit boxes
when they submit the imformation it gets added into my SQL database.
does anyone know how to get the Date and Time when they insert the information and store in another column of type datetime in SQL database
the web app is written in C#
hope someone can help
thanks
View 4 Replies
View Related
Jun 20, 2006
Good day,
I have seen in Enterprise manager there is a toll that can script the all tables in a database, but nothing that can generate the insert statements for all the rows in each table in a secified database.
Does any one know of a application, plug in, script that can generate the insert statments for all the tables in a database?
Please someone help, this is driving me insane.
Thanks
View 5 Replies
View Related
May 21, 2015
I work with sql server 2008 on a database.we have export schema and datas with the command export datas
click rigth on database => tasks => generate scripts => select all object => click advanced => select type of data to script => schema and data
Now we have a file with all datas and schema That's perfect ...But how i can insert the file in a other database?ok i can copy paste all datas in management studio and press f5 but when i do this the management studio fail because the size of the file is > 200 mega !
View 3 Replies
View Related
Sep 25, 2007
i have 2 server named A and B
in A server have database server and B have database server
in A have database named A1 with table TA1 and in B have database named B1 with table TB1
i want if i insert data into database A1 table TA1 in server A, database B1 table TB1 in server B will insert the same data to
how can do that with trigger or other ways
thx u
View 2 Replies
View Related
Apr 14, 2008
Hi,
Good morning to all.My table: User_Group_Map(UserID UNIQUEIDENTIFIER,GroupID UNIQUEIDENTIFIER)
Now, I want to write one stored procedure that can insert rows into the above table, but more number of rows at-once.
Means, the program should allow multiple insertions without the need to call the stored procedure from front-end more number of times.
Can anyone please help me on this...
Thanks in advance...Ashok kumar.
View 3 Replies
View Related
Jun 7, 2008
hellohow are you all ?I want to insert ,select update date in database these data contains special chars like ' & _ <> and so onso is there any way to handle this issue ? please help methanks a lot
View 3 Replies
View Related
Aug 8, 2000
hello!
i'm an sql server beginer. i was wondering if some of you guys can help
me out. i need for the sql server to be able to read an outside file (just text) and be able to run a script that will insert it in the database. it's a dcc output file. we've tried running this script:
DROP TABLE tests
go
DECLARE @SQLSTR varchar(255)
SELECT @SQLSTR = 'ISQL -E -Q"dbcc checkdb(master)"'
CREATE TABLE tests (Results varchar(255) NOT NULL)
INSERT INTO tests EXEC('master..xp_cmdshell ''ISQL -E -Q"dbcc checkdb(master)"''')
and it's running good but the problem is the results of the dbcc here did not come from a file but directly after executing the dcc command. is there a way to do it?
thank's for the help!
View 1 Replies
View Related
Sep 28, 2015
I've never worked with a column that's defined as a binary data type. (In the past if ever we had to include a photo we stored a link to the JPG/BMP/PNG/whatever into a column, but never actually inserted or updated a column with binary data.But now I've got to do that. So how do you put data into a column defined as BINARY(4096)?
View 3 Replies
View Related
Nov 14, 2007
I have a web form with a text field that needs to take in as much as the user decides to type and insert it into an nvarchar(max) field in the database behind. I've tried using the new .write() method in my update statement, but it cuts off the text after a while. Is there a way to insert/update in SQL 2005 this without resorting to Bulk Insert? It bloats the transaction log and turning the logging off requires a call to sp_dboptions (or a straight-up ALTER DATABASE), which I'd like to avoid if I can.
View 6 Replies
View Related
Nov 16, 2006
Hello Friends,
I have a problem with ASP.net with dynamic data transfer from asp page to microsoft sql server 2000. For example , I have asp
web page with one text field and a buttion.
When I click the buttion, the value entered in the text field should be transfered from the text field to database.
Kindly See the following section c# code .....
SqlConnection objconnect = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand();
cmd.Connection = objconnect;
cmd.CommandText = " select * from Table_Age where Age = @Age";
cmd.CommandType = CommandType.Text;
SqlParameter parameter = new SqlParameter();
parameter.ParameterName = "@Age";
parameter.SqlDbType = SqlDbType.VarChar;
parameter.Direction = ParameterDirection.Output;
parameter.Value = TextBox1.Text;
objconnect.Open(); // Add the parameter to the Parameters collection.
cmd.Parameters.Add(parameter);
SqlDataReader reader = cmd.ExecuteReader();
********************this section c# code is entered under the button control************************************
connection string is mentioned in the web.config file.
In the above c# code , I have a text field , where I entered the age , the value entered in the text field should be sent to
database. I have used SqlParameter for selecting the type of data should be sent from ASP.NET 2.0 to the microsoft sql server 2000. I am facing a problem
where I am unable to sent the random datas from a text field to the database server.
I have a created a database file in the microsoft server 2000.after the excution of the fIeld value is assinged to NULL in the main database i.e microsoft the sql server 2000.Can anyone help with this issue.My mail id phijop@hotmail.com- PHIJO MATHEW PHILIP.
View 1 Replies
View Related
Apr 2, 2008
I'm importing data form an Excel file to a Sql Server Database. Some of the data imported represents time as a double type so i convert the times into DateTime to be inserted into the database. The time values that aren't available in the Excel file are 0.. so what i want to do is insert null into the database for all the values that are 0 in the excel file... How do i do that based on this code i have so far:protected void ButtonImport_Click(object sender, EventArgs e){PanelUpload.Visible = false;PanelView.Visible = false;PanelImport.Visible = true;LabelImport.Text = "";OleDbCommand objCommand = new OleDbCommand();objCommand = ExcelConnection(); OleDbDataReader reader;reader = objCommand.ExecuteReader(); while (reader.Read()){DateTime? in_1 = null;DateTime? out_1 = null;DateTime? in_2 = null;DateTime? out_2 = null; int emp_id = Convert.ToInt32(reader["emp_id"]);DateTime date_entry = Convert.ToDateTime(reader["date_entry"]);if (Convert.ToDouble(reader["in_1"]) != 0)in_1 = ConvertDoubleToDateTime((double)reader["in_1"]);if (Convert.ToDouble(reader["out_1"]) != 0)out_1 = ConvertDoubleToDateTime((double)reader["out_1"]);if (Convert.ToDouble(reader["in_2"]) != 0)in_2 = ConvertDoubleToDateTime((double)reader["in_2"]);if (Convert.ToDouble(reader["out_2"]) != 0)out_2 = ConvertDoubleToDateTime((double)reader["out_2"]); ImportIntoAttendance(emp_id, date_entry, in_1, out_1, in_2, out_2);} reader.Close();}protected void ImportIntoAttendance(int emp_id, DateTime date_entry, DateTime? in_1, DateTime? out_1, DateTime? in_2, DateTime? out_2){ SqlDataSource AttendanceDataSource = new SqlDataSource();AttendanceDataSource.ConnectionString = ConfigurationManager.ConnectionStrings["SalariesConnectionString1"].ToString();AttendanceDataSource.InsertCommandType = SqlDataSourceCommandType.Text;AttendanceDataSource.InsertCommand = "INSERT INTO Attendance (emp_id, date_entry, in_1, out_1, in_2, out_2) " +"VALUES ('" + emp_id + "', '" + date_entry + "', '" + in_1 + "', '" + out_1 + "', " +"'" + in_2 + "', '" + out_2 + "')"; int rowsAffected = 0;try{rowsAffected = AttendanceDataSource.Insert();}catch(Exception ex){LabelImport.Text += "<font color=red>" + ex + "</font><br />";} }private DateTime ConvertDoubleToDateTime(double dbTime){string[] SplitTime = dbTime.ToString().Split('.');string hours = SplitTime[0];string minutes = String.Empty;string time = String.Empty; if (dbTime.ToString().IndexOf('.') != -1){if (SplitTime[1].Length >= 1){if (SplitTime[1].Length == 1)minutes = Convert.ToString(Convert.ToDouble(SplitTime[1]) * 10);else if (SplitTime[1].Length > 1)minutes = SplitTime[1];}}elseminutes = "00";time = hours + ":" + minutes;return Convert.ToDateTime(time);}
View 3 Replies
View Related
Feb 1, 2006
hi ALL !!!
How can I insert Date in SQL Server 2000 database(table ) from ASP.NET 1.1. Program??
pls send me code if u can
pls help me ..
View 2 Replies
View Related
May 8, 2015
i would like to know it's possible to find all transaction(insert, delete,update) on a database for a day. if yes what can i do.
View 2 Replies
View Related
Nov 5, 2007
I have two VB.NET dataclient program A abd B.
What i want to do is .. to find the best way to insert the high speed data( that comes at every 10 ms) to the sql server express database table .
I have two options to store the data in the table . One is to insert all the data in one row , the other is to divide it into many rows in the same table . In approach A i will get like 10 records per second and in approach B i may get i may get 30 - 50 records per second based on the amount of data that is comming . i.e i am creating a new row in the table for every extra column added in Approach A and duplication the other columns.
I wanted to find the better way to insert the data based on the performace metrics like CPU usage and memory usage.
View 3 Replies
View Related
Oct 29, 2015
I actually work in an organisation and we have to find a solution about the data consistancy in the database. our partners use to send details to the organisation and inserted directly in the database, so we want to create a new database as a buffer database to insert informations from the partners then make an update to the main database. is there a better solution instead of that?
View 6 Replies
View Related
Oct 26, 2015
I am using two database server. Both are sql server.Â
My task is :I want to insert data from server 1 table to server 2 table and update same when modified the existing data from server 1. is it possible to do the integration in single package.
I know to do insert and update seperately by ssis but need to do same with single task.Â
View 5 Replies
View Related
Apr 15, 2007
Hi,
I have two SQL Express database and I want to do two things. One is to transfer a table over to the other database. Two, move the files from one table in one database to another. Please let me know when you get a chance.
Thanks,
Kyle
View 8 Replies
View Related
Jun 14, 2006
I was able to connect to the SQL Database Pension with table clients with table values: ID, State, Name.'Create(connection)Dim conn As New Data.SqlClient.SqlConnection(ConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString)'open connectionconn.Open()However, I'm not sure how to insert a new row with an incremental ID number and a new State and Name.Sorry, I'm really new with VWD.
View 1 Replies
View Related
May 22, 1999
Hi guys,
I have two sql servers one is Nt server another one is Nt workstation,i am able to admin from both sides.but i don't know how to insert/update one database table to another database table, pls. give me some ideas for this.
Thanks in Advance
Nellai
View 1 Replies
View Related
Mar 19, 2008
Hi,
We have different databases on the same server: Whrs001, Whrs002, etc. All databases have the same structure.
Suppose i have a table "location"
create table location
( location_id int not null primary key,
location_name varchar(50) not null )
I need to inserts data in "location" tables of different databases. But these inserts needs to be across databases. For example from the "Whrs003" database I need to insert data (location_id=123, location_name='markham') in "location" table of "Whrs001" database.
So my thinking is to defined a stored proc which has database name as an argument:
create procedure location_insert
@a_database_name varchar(100),
@a_location_id int,
@a_location_name varchar(50)
as
...
So for the above example the call will be :
exec location_insert 'Whrs001', 123, 'markham'
What would be the actual insert statement in this case? And what things i neeed to take care fo to make sure it always execute successfully?
Thanks
View 5 Replies
View Related
May 7, 2007
hi
i am using this queries is
Insert into excelb.B.dbo.Emp(Employee_Name,Emp_addr) Values (@Employee_Name,@Emp_Addr) select * from excelb.A.dbo.Emp
excelb - server name
now my problem is a server to another server insert the data that not acces the data and i am using different password the servers- but same pasword are insert the data
plz help me
bye
elango
View 4 Replies
View Related
Feb 26, 2015
I am writing a query to return some production data. Basically i need to insert either 1 or 2 rows into a Table variable based on a decision as to does the production part make 1 or 2 items ( The Raw data does not allow for this it comes from a look up in my database)
I can retrieve all the source data i need easily but when i come to insert it into the table variable i need to insert 1 record if its a single part or 2 records if its a twin part. I know could use a cursor but im sure there has to be an easier way !
Below is the code i have at the moment
declare @startdate as datetime
declare @enddate as datetime
declare @Line as Integer
DECLARE @count INT
set @startdate = '2015-01-01'
set @enddate = '2015-01-31'
[Code] .....
View 1 Replies
View Related
Apr 29, 2007
ok, I am on Day 2 of being brain dead.I have a database with a table with 2 varchar(25) columns I have a btton click event that gets the value of the userName, and a text box.I NEED to insert a new row in a sql database, with the 2 variables.Ive used a sqldatasource object, and tried to midify the insert parameters, tried to set it at the button click event, and NOTHING is working. Anyone have a good source for sql 101/ASP.Net/Braindead where I can find this out, or better yet, give me an example. this is what I got <%@ Page Language="C#" %><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><script runat="server"> protected void runit_Click(object sender, EventArgs e) { //SqlDataSource ID = "InsertExtraInfo".Insert(); //SqlDataSource1.Insert(); } protected void Button1_Click1(object sender, EventArgs e) { SqlDataSource newsql; newsql.InsertParameters.Add("@name", "Dan"); newsql.InsertParameters.Add("@color", "rose"); String t_c = "purple"; string tempname = Page.User.Identity.Name; Label1.Text = tempname; Label2.Text = t_c; newsql.Insert(); }</script><html xmlns="http://www.w3.org/1999/xhtml" ><head runat="server"> <title>mini update</title></head><body> <form id="form1" runat="server"> name<asp:TextBox ID="name" runat="server" OnTextChanged="TextBox2_TextChanged"></asp:TextBox><br /> color <asp:TextBox ID="color" runat="server"></asp:TextBox><br /> <br /> <asp:Button ID="Button1" runat="server" OnClick="Button1_Click1" Text="Button" /> <br /> set lable =><asp:Label ID="Label1" runat="server" Text="Label" Width="135px" Visible="False"></asp:Label><br /> Lable 2 => <asp:Label ID="Label2" runat="server" Text="Label"></asp:Label><br /> Usernmae=><asp:LoginName ID="LoginName1" runat="server" /> <br /> <br /> <br /> <br /> <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConflictDetection="CompareAllValues" ConnectionString="<%$ ConnectionStrings:newstring %>" DeleteCommand="DELETE FROM [favcolor] WHERE [name] = @original_name AND [color] = @original_color" InsertCommand="INSERT INTO [favcolor] ([name], [color]) VALUES (@name, @color)" OldValuesParameterFormatString="original_{0}" SelectCommand="SELECT [name], [color] FROM [favcolor]" UpdateCommand="UPDATE [favcolor] SET [color] = @color WHERE [name] = @original_name AND [color] = @original_color"> <DeleteParameters> <asp:Parameter Name="original_name" Type="String" /> <asp:Parameter Name="original_color" Type="String" /> </DeleteParameters> <UpdateParameters> <asp:Parameter Name="color" Type="String" /> <asp:Parameter Name="original_name" Type="String" /> <asp:Parameter Name="original_color" Type="String" /> </UpdateParameters> <InsertParameters> <asp:InsertParameter("@name", "Dan", Type="String" /> <asp:InsertParameter("@color", "rose") Type="String"/> </InsertParameters> </asp:SqlDataSource> <asp:GridView ID="GridView1" runat="server" AllowPaging="True" AllowSorting="True" AutoGenerateColumns="False" DataKeyNames="name" DataSourceID="SqlDataSource1"> <Columns> <asp:CommandField ShowDeleteButton="True" ShowEditButton="True" ShowSelectButton="True" /> <asp:BoundField DataField="color" HeaderText="color" SortExpression="color" /> <asp:BoundField DataField="name" HeaderText="name" ReadOnly="True" SortExpression="name" /> </Columns> </asp:GridView> </form></body></html>
View 1 Replies
View Related
Jul 17, 2006
I'm not sure what the problem is. I am not getting any errors, but I can't get this code to insert into my SQL db. I've checked the permissions on the database and table, and it looks fine.
Is there something wrong with this code? I'm trying to switch from VB to C#, so it's still new to me. I've used the connection string in another APP so I know it works.
If I'm not getting an asp.net error, does that point to a problem with the DB? Thanks.
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection Conn;SqlCommand Command;
Conn = new SqlConnection();Conn.ConnectionString = ConfigurationManager.AppSettings["ConnectionString"];Command = new SqlCommand();
Command.CommandText = "INSERT INTO [tbl_Test] ([test_name], [test_email]) VALUES (@test_name, @test_email)";
Command.CommandType = CommandType.Text;Command.Connection = Conn;Command.Parameters.Add("test_name", tbName.Text);Command.Parameters.Add("test_email", tbEmail.Text);
try
{
Command.Connection.Open();Command.ExecuteNonQuery();
}
catch (Exception ex)
{
lError.Text = ex.Message;
}
finally
{
Command.Connection.Close();pSubscribe.Visible = false;lThanks.Visible = true;
}
View 3 Replies
View Related
Apr 10, 2008
Hi,
I am getting xml data from a webservice.. and in that xml data there in field called State but on the system that we are getting the data from has a text box where the user can enter NC or North carolina.. But our system is set up to just accept a two letter character. like NC.. So suppose if the user sends North carolina instead of NC the nothing takes places on our system cause we get an error saying that Two many characters..
SO i am looking for ideas that will solve this problem but have the state column accept just 2 letters
any help will be appreciated
KAren
View 2 Replies
View Related
Jun 15, 2008
My problem is that when I add a question and the question contains a ' (For instance: I'm going to the store), an error message shows up for 'm from I'm. Here is my code. SqlConnection myConnection = new SqlConnection("Server=???;Database=???;Persist Security Info=True;User ID=???;Password=???"); SqlCommand insertCmd = new SqlCommand(); insertCmd.CommandType = System.Data.CommandType.Text; insertCmd.CommandText = "INSERT INTO TestQuestions (unitChapterID, question, answerA, answerB, answerC, answerD, answer) VALUES (" + int.Parse(DropDownList3.Text.ToString()) + ", '" + questionAddBox.Text.ToString() + "', '" + aAddBox.Text.ToString() + "', '" + bAddBox.Text.ToString() + "', '" + cAddBox.Text.ToString() + "', '" + dAddBox.Text.ToString() + "', '" + answerAddBox.Text.ToString() + "')"; insertCmd.Connection = myConnection; myConnection.Open(); insertCmd.ExecuteNonQuery(); myConnection.Close();
View 2 Replies
View Related
Aug 27, 2006
I Have an error: Server Error in '/quanlythietbi' Application. INSERT statement conflicted with COLUMN FOREIGN KEY constraint 'FK_yeucau_nhanvien'. The conflict occurred in database 'equipment', table 'nhanvien', column 'manv'. The statement has been terminated. Source Error: Line 129:mycommand.Parameters.Add(new SqlParameter("@noidung_yc1",System.Data.SqlDbType.Text));
Line 130:mycommand.Parameters["@noidung_yc1"].Value = TextBox1.Text;
Line 131:int i = mycommand.ExecuteNonQuery();
Line 132:if (i>0)
Line 133:{and this is my code:string sqlstring = "Select * from yeucau where ngayGiaiQuyetxong='"+ Label8.Text +"' and date_yc='" + Label7.Text + "' and manv_yc='"+ TextBox2.Text + "' and noidung_yc='"+ TextBox1.Text+ "'";myconnection = new SqlConnection(stringconn);mycommand = new SqlCommand(sqlstring,myconnection);myconnection.Close();myconnection.Open();mycommand = new SqlCommand(insertquery,myconnection); mycommand.Parameters.Add(new SqlParameter("@ngayGiaiQuyetxong1",System.Data.SqlDbType.Char,10));mycommand.Parameters["@ngayGiaiQuyetxong1"].Value = Label8.Text;mycommand.Parameters.Add(new SqlParameter("@date_yc1",System.Data.SqlDbType.SmallDateTime));mycommand.Parameters["@date_yc1"].Value = Label7.Text;mycommand.Parameters.Add("@manv_yc1",System.Data.SqlDbType.Char,10);mycommand.Parameters["@manv_yc1"].Value = TextBox2.Text;mycommand.Parameters.Add(new SqlParameter("@noidung_yc1",System.Data.SqlDbType.Text));mycommand.Parameters["@noidung_yc1"].Value = TextBox1.Text;int i = mycommand.ExecuteNonQuery();if (i>0){lbcheck.Text = "Ä?ã Cáºp Nháºt Yêu Cầu.";} --------------------------------------------------------------------------------------------------------------------------------I don't know what I must do to repair it :(
View 2 Replies
View Related
Feb 27, 2007
What is wrong with this code the dropdowlist mainlyusing System;using System.Data;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;using System.Data.SqlClient;public partial class NewAccount : System.Web.UI.Page{ protected void Page_Load(object sender, EventArgs e) { } protected void NaccountButton_Click(object sender, EventArgs e) { if (Page.IsValid) { //Define data objects SqlConnection conn; SqlCommand comm; //read from web config string connectionString = ConfigurationManager.ConnectionStrings["OneBank"].ConnectionString; //Initialize connection conn = new SqlConnection(connectionString); //create command comm =new SqlCommand( "INSERT INTO Customer (FirstName, LastName, Street, City, State," + "Zip, Phone, Payee,AccountType)" + "VALUES(FirstName, LastName, Street, City," + "State, Zip, Phone, Payee,AccountType)", conn); //add parameters comm.Parameters.Add("@FirstName", System.Data.SqlDbType.NVarChar, 50); comm.Parameters["@FirstName"].Value=Firstname.Text; comm.Parameters.Add("@LastName", System.Data.SqlDbType.NVarChar, 50); comm.Parameters["@LastName"].Value=lastname.Text; comm.Parameters.Add("@Street", System.Data.SqlDbType.NVarChar, 50); comm.Parameters["@Street"].Value=street.Text; comm.Parameters.Add("@City", System.Data.SqlDbType.NVarChar, 50); comm.Parameters["@City"].Value=city.Text; comm.Parameters.Add("@State", System.Data.SqlDbType.NVarChar, 50); comm.Parameters["@State"].Value=state.Text; comm.Parameters.Add("@Phone", System.Data.SqlDbType.Int); comm.Parameters["@Phone"].Value=phone.Text; comm.Parameters.Add("@AccountType", System.Data.SqlDbType.NVarChar, 50); comm.Parameters["AccountType"].Value = dropdownlist1.SelectedValue.ToString(); //Enclose database in try catc finally try { //open connection conn.Open(); //execute the command comm.ExecuteNonQuery(); //reload query Response.Redirect("NewAccount.aspx"); } catch { //Display error Errormessage.Text= "Error submitting request!"; } finally { conn.Close(); } } }}
This is the table where thisis going
customer ------------- customerID pk generated automatically firtsname lastname street city statezipphoneaccountType
View 3 Replies
View Related