Documentation
 
 
 

25.11. Inserting Records in a Database

You can add records by making use of the SQL Insert command. In order to do this with EnterpriseDB and .NET you need to do the following:

  • Creating and opening a database connection

  • Creating a database command that represents the insert statement to be executed

  • Execute the insert command using the ExecuteNonQuery() method of EDBCommand.

The example below shows how to add a new employee to our sample emp table we would do something like the following:

Example 25-6. Example - Inserting a Database Record

   
<% @ Page Language="C#" Debug="true"%>
<% @Import Namespace="EnterpriseDB.EDBClient" %>
<% @Import Namespace="System.Data" %>

<script language="C#" runat="server" >

private void Page_Load(object sender, System.EventArgs e)
{
	string strConnectionString = ConfigurationSettings.AppSettings
	["DB_CONN_STRING"];
	EDBConnection conn = new EDBConnection(strConnectionString);	
			
	try {
		conn.Open();
		string strInsertEmployee = "INSERT INTO emp(empno,ename) 
		VALUES(:EmpNo, :EName)";
		EDBCommand cmdInsert = new EDBCommand(strInsertEmployee,conn);
			
		cmdInsert.Parameters.Add(new EDBParameter(":EmpNo", 
		EDBTypes.EDBDbType.Integer));
		cmdInsert.Parameters[0].Value = 1234;	
			
		cmdInsert.Parameters.Add(new EDBParameter(":EName", 
		EDBTypes.EDBDbType.Text));
		cmdInsert.Parameters[1].Value = "EDB";		

		cmdInsert.ExecuteNonQuery();
		Response.Write("Record inserted successfully");	
	    }
			
	catch(Exception exp) { 
		Response.Write(exp.ToString());
	}
	finally {
		conn.Close();
	}
}

</script>	
   

Save the file as "insertEmployee.aspx" and save it in your default web server's root then access it via typing http://localhost/insertEmployee.aspx in your web browser. If no errors are generated then a "Record inserted successfully" message should be shown.

25.11.1. Inserting Records in a Database - Explanation

The insert command is stored in the variable strInsertEmployee. The values prefixed with ":" are placeholders for EDBParameters that are instantiated, assigned values and then added to the insert command's parameter collection in the following statements. The actual insert command is executed by calling the ExecuteNonQuery() method of the cmdInsert object. You are making use of this method since you are not returning any records from the database.

 
 ©2004-2007 EnterpriseDB All Rights Reserved