.

How To: Connect to SQL using C# and SELECT, INSERT or any other SQL STATEMENT?

by Simon Deshaies 12. March 2008 06:10

I started a thread on the asp.net forums a while back wanting to share with the others a easy way to connect to SQL. Since then I perfected quite a bit the code and made it a class.cs file, that can be up and running in a few minutes.

Connecting to SQL using the design view in visual studio is quite easy and straight forward. I found to be somewhat limited though. Having a class that you can invoke in all your application and in other classes is the works.

Here I demonstrate how to use C# in a class file to connect to SQL, and INSERT, SELECT or UPDATE an existing SQL database. In this example I will be using the Microsoft SQL Express Server. Also the connection string in this example is using integrated SQL security; if you need to connect to an external server or any other king of SQL server go to http://connectionstrings.com to get the replacement connection string code.

First off unlike asp.net insert you don’t use a connection string in the web.config, you can but for sake of simplicity it does not. If that’s your goal, the class is commented on hot to do that.

Add an .cs file to your solution and paste the following code. Be weary of the namespace either rename or remove it.

using System;
using System.Configuration;

namespace ToolBox
{
    /// <summary>
    /// SqlConnection class connects to SQL and when
    /// disposed it closes the connection to SQL.
    /// </summary>
    public sealed class SqlConnection : IDisposable
    {
        #region Properties
        public System.Data.SqlClient.SqlConnection Connection { get; set; }
        public System.Data.SqlClient.SqlDataReader DataReader { get; set; }
        public System.Data.SqlClient.SqlCommand Command { get; set; }
        #endregion

        #region Constructors
        /// <summary>
        /// Instanciate SqlConnection and open connection to SQL Server
        /// </summary>
        public SqlConnection()
        {
            //New up the SqlConnection class
            if (Connection == null)
                Connection = new System.Data.SqlClient.SqlConnection();

            // Assign the connection string
            //
            // It can be also saved in the .config file
            //<connectionStrings>
            //<add name="MyConnectionString" 
            //      connectionString="server=SERVERNAME;database=DATABASENAME;Trusted_Connection=True;"
            //      providerName="System.Data.SqlClient" />
            //</connectionStrings>
            //Uncomment the following line to get it form the configuration file
            //Connection.ConnectionString = ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;

            Connection.ConnectionString = "server=SERVERNAME;database=DATABASENAME;Trusted_Connection=True;";

            //Open the connection
            Open();
        }
        #endregion

        /// <summary>
        /// Opens a connection to SQL
        /// </summary>
        /// <returns>Connected System.Data.SqlClient.SqlConnection</returns>
        private void Open()
        {
            //Attempt to connect and catch exception
            if (Connection.State != System.Data.ConnectionState.Open)
                try
                {
                    //Try to connect with a short timeout and pooling
                    Connection.ConnectionString = 
                        String.Format(
                        "Min Pool Size=1;Max Pool Size=10;Connect Timeout=4;{0}"
                        , Connection.ConnectionString);
                    Connection.Open();
                }
                catch
                {
                    //If connection failed, try again without pooling and a linger timeout
                    if (Connection.State != System.Data.ConnectionState.Closed)
                        Connection.Close();

                    Connection.ConnectionString = 
                        String.Format(
                        "Pooling=false;Connect Timeout=45;{0}"
                        , Connection.ConnectionString);
                    Connection.Open();
                }
        }

        #region IDisposable Members

        // Track whether Dispose has been called.
        private Boolean disposed = false;

        /// <summary>
        /// Implement IDisposable.

        /// Do not make this method virtual.
        /// A derived class should not be able to override this method.
        /// </summary>
        public void Dispose()
        {
            Dispose(true);
            // This object will be cleaned up by the Dispose method.
            // Therefore, you should call GC.SupressFinalize to
            // take this object off the finalization queue
            // and prevent finalization code for this object
            // from executing a second time.
            GC.SuppressFinalize(this);
        }

        /// <summary>
        /// Dispose(bool disposing) executes in two distinct scenarios.
        /// If disposing equals true, the method has been called directly
        /// or indirectly by a user's code. Managed and unmanaged resources
        /// can be disposed.
        /// If disposing equals false, the method has been called by the
        /// runtime from inside the finalizer and you should not reference
        /// other objects. Only unmanaged resources can be disposed.
        /// </summary>
        /// <param name="disposing"></param>
        private void Dispose(bool disposing)
        {
            // Check to see if Dispose has already been called.
            if (!this.disposed)
            {
                lock (this)
                {
                    // If disposing equals true, dispose all managed
                    // and unmanaged resources.
                    if (disposing)
                    {
                        Connection.Dispose();
                        if (DataReader != null)
                            DataReader.Dispose();
                        if (Command != null)
                            Command.Dispose();
                    }
                    // Note disposing has been done.
                    disposed = true;
                }
            }
        }

        /// <summary>
        /// Use C# destructor syntax for finalization code.
        /// This destructor will run only if the Dispose method
        /// does not get called.
        /// It gives your base class the opportunity to finalize.
        /// Do not provide destructors in types derived from this class.
        /// </summary>
        ~SqlConnection()
        {
            Dispose(false);
        }

        #endregion
    }
}

IDisposable Interface

Since the class contains property that implement IDisposable interface, the rule is that the class also has to implement it. IDisposable offer 2 very nice way to use the calss:

1. With a using statement:

using (SqlConnection connection = new SqlConnection())
{
    //Do something
}

2. With try / finally statement: 

SqlConnection connection = new SqlConnection();
try
{
    //Do something
}
finally
{
    connection.Dispose();
}

Usage

Here are some examples on how to use the class, in the examples I prefer the using statement.

SELECT:

using (SqlConnection connection = new SqlConnection())
{
    connection.Command = connection.Connection.CreateCommand();
    connection.Command.CommandType = System.Data.CommandType.Text;
    connection.Command.Parameters.Add("@Name", System.Data.SqlDbType.NVarChar);
    connection.Command.Parameters["@Name"].Value = "Simon";
    connection.Command.CommandText = @"SELECT *FORM [dbo].[table1] WHERE [Name] = @Name";
    connection.DataReader = connection.Command.ExecuteReader();
    while (connection.DataReader.Read())
    {
        //Do something
    }
}

INSERT:

using (SqlConnection connection = new SqlConnection())
{
     connection.Command = connection.Connection.CreateCommand();
     connection.Command.CommandType = System.Data.CommandType.Text;
     connection.Command.Parameters.Add("@Value", System.Data.SqlDbType.NVarChar);
     connection.Command.Parameters["@Value"].Value = "Simon";
     connection.Command.CommandText = @"INSERT INTO [dbo].[table1] VALUES (@Name)";
     connection.Command.ExecuteNonQuery();
}

Comments

4/5/2008 11:29:24 AM #

shekhar kadam

just great men...

shekhar kadam India

4/17/2008 12:36:21 PM #

Dave

Sick!! Great Job!

Dave Canada

10/20/2008 2:31:37 PM #

Max Lopez

Hello Simon Deshaies,

I have to say your code is great, I have been building a database system for quite sometime now using visual basic and am looking to update it with a more robust and powerful engine. I have seen your class implementation and I think its great. I was curious about a couple of things, I have honestly not written much code in C# for quite sometime, primarily because of the investment my company made with Visual Basic. What I am hoping you can help me with is how do I use your class instance above with the "SELECT" sql statement to assign the record values into text boxes.

I have payroll program and I wish to type in a social and view their payroll information. I would really just like to see the code to implement the SQL statement with your class to assign the record to the textbox1.text object. I have seen how to insert, and with that pretty much can already view and assume how to update the table, but I have not been able to deduce how to view the record with a text box.

This is what I saw on a previous forum post you had created.
MySqlConnection mySql = new MySqlConnection();
            mySql.CreateConn();
            mySql.Command = mySql.Connection.CreateCommand();
            mySql.Command.CommandText = "INSERT INTO ZTABLE (NAME, NAMELAST) VALUES (@textBox1, @textBox2)";

            mySql.Command.Parameters.Add("@textBox1", SqlDbType.VarChar);
            mySql.Command.Parameters["@textBox1"].Value = textBox1.Text;
            mySql.Command.Parameters.Add("@textBox2", SqlDbType.VarChar);
            mySql.Command.Parameters["@textBox2"].Value = textBox2.Text;

            mySql.Command.ExecuteNonQuery();

            mySql.Command.Dispose();
            mySql.Connection.Close();
            mySql.CloseConn();

As I said it worked great to insert the information, but I was hoping you could help me to view current data in the table and assign it to a text box.

Max Lopez United States

10/20/2008 9:52:23 PM #

Simon Deshaies

Hi Max,

First, thank you. I'm verry happy to be able to help fellow developers.

To be able to assign a value for a database to a text box there are many to do this. You can ether use a Out parameter or a DataReader.

I prefer the DataReader, well because I'm more use to it...

Here an example.

MySqlConnection mySql = new MySqlConnection();
mySql.CreateConn();
mySql.Command = mySql.Connection.CreateCommand();
mySql.Command.CommandText = Sring.Format("SELECT [dbo].[Users].[Name] FROM [dbo].[ZTABLE] WHERE [dbo].[Users].[UserId] = {0}", MyUserIdTextBox.Text);
mySql.DataReader = mySql.Command.ExecuteDataReader();
while(mySql.DataReader.Read())
{
    MyUserNameTextBox.Text = Convert.ToString(mySql.DataReader[0]);
}
mySql.DataReader.Close();
mySql.Command.Dispose();
mySql.CloseConn();

Hope this helps. Let me know. If you need any clarifications, well, just post! ;)

Simon

Simon Deshaies Canada

11/21/2008 12:03:36 PM #

christophe Goasduff

Bonjour Simon

I quite new to asp.net and so far I have been using the "SqlDataSource" component which I have to say is very easy and handy.

I am trying to move from that and use your method, but I am not too sure how migrate my InsertCommand from the ASPX to the code behind page since my InsertCommand is not that simple. It uses IF statement and Joints. (if a particular radiobutton is selected it should execute a particular statement if another is seleted it executes another statement) I can understand your sample file but cannot apply it to my situation. A bit of help would be much appreciated.

Here is my SqlDataSource:

  <asp:SqlDataSource ID="SqlDataSourceInsert" runat="server" ConnectionString="<%$ ConnectionStrings:IMS_DBConnectionString %>"
  InsertCommand="
  IF @ctrl_user_role = 2 BEGIN
  
  INSERT INTO tbl_user (user_name, user_surname, user_email, user_pw, dpt_id, user_review)
  VALUES(@ctrl_user_name, @ctrl_user_surname, @ctrl_user_email, @ctrl_user_pw, @ctrl_user_dpt_id,@Ctrl_HF_userReview)

  INSERT INTO tbl_user_role (user_id,role_id)
  VALUES(IDENT_CURRENT('tbl_user'),@ctrl_user_role)

  INSERT INTO tbl_dep_reviewers(dpt_id,user_id)
  VALUES(@ctrl_user_dpt_id,IDENT_CURRENT('tbl_user'))
  
  INSERT INTO tbl_dpt_users(dpt_id,user_id)
  VALUES(@ctrl_sub_dpt,IDENT_CURRENT('tbl_user')); END
  
  IF @ctrl_user_role = 1 AND @ctrl_user_review = 0  BEGIN
  
  INSERT INTO tbl_user (user_name, user_surname, user_email, user_pw, dpt_id, user_review)
  VALUES(@ctrl_user_name, @ctrl_user_surname, @ctrl_user_email, @ctrl_user_pw, @ctrl_user_dpt_id, @ctrl_user_review)
  
  INSERT INTO tbl_user_role (user_id,role_id)
  VALUES(IDENT_CURRENT('tbl_user'),@ctrl_user_role)
  
  INSERT INTO tbl_dpt_users(dpt_id,user_id)
  VALUES(@ctrl_sub_dpt,IDENT_CURRENT('tbl_user')); END
  
  
  IF @ctrl_user_role = 1 AND @ctrl_user_review = 1 BEGIN
  
  INSERT INTO tbl_user (user_name, user_surname, user_email, user_pw, dpt_id, user_review, user_reviewer)
  VALUES(@ctrl_user_name, @ctrl_user_surname, @ctrl_user_email, @ctrl_user_pw, @ctrl_user_dpt_id, @ctrl_user_review, @ctrl_user_reviewer)
  
  INSERT INTO tbl_user_role (user_id,role_id)
  VALUES(IDENT_CURRENT('tbl_user'),@ctrl_user_role)
  
  INSERT INTO tbl_dpt_users(dpt_id,user_id)
  VALUES(@ctrl_sub_dpt,IDENT_CURRENT('tbl_user')); END ">
  
  
  <InsertParameters>
  <asp:ControlParameter Name="ctrl_user_name" ControlID="Txt_user_name"/>
  <asp:ControlParameter Name="ctrl_user_surname" ControlID="Txt_user_surname"/>
  <asp:ControlParameter Name="ctrl_user_email" ControlID="Txt_user_email"/>
  <asp:ControlParameter Name="ctrl_user_pw" ControlID="Txt_user_pw"/>
  <asp:ControlParameter Name="ctrl_user_role" ControlID="check1"/>  
  <asp:ControlParameter Name="ctrl_user_dpt_id" ControlID="dropDown_choose_dpt"/>
  <asp:ControlParameter Name="ctrl_user_review" ControlID="RBL_user_review"/>
  <asp:ControlParameter Name="ctrl_user_reviewer" ControlID="DDL_user_reviewer"/>
  <asp:ControlParameter Name="ctrl_HF_userReview" ControlID="HF_userReview" />
  <asp:ControlParameter Name="ctrl_sub_dpt" ControlID="CheckBoxList_sub_dpt" />
  
  
  </InsertParameters>
</asp:SqlDataSource>




I have another question if I may. How would you populate dynamicaly let's say a dropdownlist if you don't use a "SqlDataSource" Would you still use <aspLaughingropDownList DataSourceID="" ? would you bind it to "mySql.DataReader" ?

Here is the SqlDataSource which populate hte DropdownList

<!--DS (SqlDS_dept) populates the drop down menu "choose department"-->

<asp:SqlDataSource ID="SqlDS_dept" runat="server" ConnectionString="<%$ ConnectionStrings:IMS_DBConnectionString %>"
        SelectCommand="SELECT * FROM [tbl_department] WHERE [dpt_subsection_of] = 0 "></asp:SqlDataSource>


Thanks a lot for

Christophe















christophe Goasduff United Kingdom

11/26/2008 5:02:03 PM #

Simon Deshaies

Christophe,

1- To move to code behind you would do something like this:
            MySqlConnection.Open();
            MySqlConnection.Command = MySqlConnection.Connection.CreateCommand();
            //Your command
            MySqlConnection.Command.CommandText = "INSERT INTO tbl_user (user_name, user_surname, user_email, user_pw, dpt_id, user_review) VALUES(@ctrl_user_name, @ctrl_user_surname, @ctrl_user_email, @ctrl_user_pw, @ctrl_user_dpt_id,@Ctrl_HF_userReview)";
            
            //Your parameter
            MySqlConnection.Command.Parameters.Add("@ctrl_user_name", SqlDbType.VarChar); //Parameter SQL Type
            MySqlConnection.Command.Parameters["@ctrl_user_name"].Value = Txt_user_name.Text;
            
            //For your condition
            if (check1.Checked)
            {
                //your code
            }

But this is not the best way to do this. I would suggest you create a stored procedure you can either create it in SQL this you make your code way more easy to maintain.

If you do not want to create a procedure in SQL Server you could do something like this:

            MySqlConnection.Open();
            MySqlConnection.Command = MySqlConnection.Connection.CreateCommand();
            
            //Set all your parameter
            MySqlConnection.Command.Parameters.Add("@ctrl_user_name", SqlDbType.VarChar); //Parameter SQL Type
            MySqlConnection.Command.Parameters["@ctrl_user_name"].Value = Txt_user_name.Text;

            //Your command
            MySqlConnection.Command.CommandText = @"
                    IF @ctrl_user_role = 2 BEGIN

                    INSERT INTO tbl_user (user_name, user_surname, user_email, user_pw, dpt_id, user_review)
                    VALUES(@ctrl_user_name, @ctrl_user_surname, @ctrl_user_email, @ctrl_user_pw, @ctrl_user_dpt_id,@Ctrl_HF_userReview)

                    INSERT INTO tbl_user_role (user_id,role_id)
                    VALUES(IDENT_CURRENT('tbl_user'),@ctrl_user_role)

                    INSERT INTO tbl_dep_reviewers(dpt_id,user_id)
                    VALUES(@ctrl_user_dpt_id,IDENT_CURRENT('tbl_user'))

                    INSERT INTO tbl_dpt_users(dpt_id,user_id)
                    VALUES(@ctrl_sub_dpt,IDENT_CURRENT('tbl_user')); END

                    IF @ctrl_user_role = 1 AND @ctrl_user_review = 0 BEGIN

                    INSERT INTO tbl_user (user_name, user_surname, user_email, user_pw, dpt_id, user_review)
                    VALUES(@ctrl_user_name, @ctrl_user_surname, @ctrl_user_email, @ctrl_user_pw, @ctrl_user_dpt_id, @ctrl_user_review)

                    INSERT INTO tbl_user_role (user_id,role_id)
                    VALUES(IDENT_CURRENT('tbl_user'),@ctrl_user_role)

                    INSERT INTO tbl_dpt_users(dpt_id,user_id)
                    VALUES(@ctrl_sub_dpt,IDENT_CURRENT('tbl_user')); END


                    IF @ctrl_user_role = 1 AND @ctrl_user_review = 1 BEGIN

                    INSERT INTO tbl_user (user_name, user_surname, user_email, user_pw, dpt_id, user_review, user_reviewer)
                    VALUES(@ctrl_user_name, @ctrl_user_surname, @ctrl_user_email, @ctrl_user_pw, @ctrl_user_dpt_id, @ctrl_user_review, @ctrl_user_reviewer)

                    INSERT INTO tbl_user_role (user_id,role_id)
                    VALUES(IDENT_CURRENT('tbl_user'),@ctrl_user_role)

                    INSERT INTO tbl_dpt_users(dpt_id,user_id)
                    VALUES(@ctrl_sub_dpt,IDENT_CURRENT('tbl_user')); END";
            MySqlConnection.Command.ExecuteNonQuery();

For the DropDownList you can either set them wil the DataReader
MySqlConnection.Open();
MySqlConnection.Command = MySqlConnection.Connection.CreateCommand();
MySqlConnection.Command.CommandType = CommandType.Text;
MySqlConnection.Command.CommandText = "SELECT something FROM [dbo].[sometable] WHERE [template] = 0 ORDER BY something";
MySqlConnection.DataReader = MySqlConnection.Command.ExecuteReader();
while (MySqlConnection.DataReader.Read())
{
raceDropDownList.Items.Add(Convert.ToString(MySqlConnection.DataReader["something"]));
}
MySqlConnection.DataReader.Close();

or a DataTable as DataSource

DataTable MyAliasDataTable = new DataTable();
SqlDataAdapter MyAliasDataAdapter = new SqlDataAdapter("SELECT [userID],[alias] FROM [dbo].[users] ORDER BY [alias]", MySqlConnection.Connection);
MyAliasDataAdapter.Fill(MyAliasDataTable);
AliasDropDownList.DataSource = MyAliasDataTable;
AliasDropDownList.DataTextField = "alias";
AliasDropDownList.DataValueField = "userID";
AliasDropDownList.DataBind();
MyAliasDataTable.Dispose();
MyAliasDataAdapter.Dispose();

Regards,

Simon

Simon Deshaies

11/30/2008 10:10:07 PM #

Jessica

Hello,

does any of you guys know how to retrieve data from a database (be it SQL or MS Access) and display the contents on a Microsoft Visual Studio Emulator? Please help.

Thanks,
Jessica

Jessica Singapore

12/1/2008 6:24:29 AM #

Natasja

Hi
The connection is great but I am a beginner and I dont follow all of it. Is there a simpler version? All I want is a class that I can call in my code behind to connect to my database. I dont want to have to put my connection string in my code behind everytime.
I usually do it like this :
SqlConnection myConnection = new SqlConnection("fullconnectionstring");
try
{
    myConnection.Open();
}
catch(Exception e)
{
    Console.WriteLine(e.ToString());
}

on every code behind where I need to connect to the database.
Thanks!

Natasja South Africa

3/13/2009 9:41:57 AM #

Eric Fleming

I am new to developing using C# and Visual Studio 2008.  I am working on a proof of concept project to use an InfoPath form connecting through a web service to submit and retrieve data from a SQL database.  The form is created and published to a SharePoint website.  This article is exactly what I am looking for to insert data into a SQL table using C#.  How can I incorporate this functionality into a web service that I created?  Do I use a web method?  I created  the IIS Virtual Directory and have it pointing to the directory that has my web service.  I was able to get this to work fundamentally using a version of the database in Access.  I need to have this working with SQL though.

any and all help is greatly appreciated.

Thanks.

Eric Fleming United States

3/19/2009 2:05:20 PM #

Simon Deshaies

Hi Eric,

The class is just c# code so it can run anywhere. Usually in .net architecture you have a place like a library or a folder containing all your utility classes, like this one.

The simplest way is to create your web service, then add a class file and copy the class in there.

Then you can access your class:
MySqlConnection MyConn = new MySqlConnection();
MyConn.Open();
etc..

I'm not too sure it this was the answer you where looking for . If not post come code (common language it is) I will get what you are trying easily.

Regards,

Simon

Simon Deshaies Canada

3/20/2009 4:45:18 AM #

Eric Fleming

Thank you for responding to my question.  I was able to use some of the examples you have posted to do a basic insert of data into an SQL Server database in the web service.  Now I am looking to just do a basic query and return of that same data back to the InfoPath form.  Since I have the connection string code for the insert I can basically use that same code for the receive.  I am looking for an example of how to code the 'select clause'.  I am also looking for the 'update clause' so I can modify existing data back to the database.

I know this may be simple coding examples but it helps me a lot to just see it in it's basic form and then I can branch off from there.

Thank you for you patience and assistance in this endeavor.

Eric Fleming United States

3/20/2009 6:33:25 AM #

Simon Deshaies

Eric,

The way you format your data returned by SQL depends on what is your method return type and data format. To answer your questions I would need to know this. As I never ever did program for InfoPath or share point. As they are evil. ;)

Thanks,

Simon


Simon Deshaies Canada

3/20/2009 8:23:36 AM #

Eric Fleming

The method return type would be a Webmethod if that is what you mean.  Everything is going to basically come back through the InfoPath form being posted as a web form.

And yes, InfoPath and SharePoint can be difficult.

Eric Fleming United States

3/22/2009 5:07:14 AM #

Simon Deshaies

Hi Eric,

I looked around and this is not very clear. I'm not a sharepoint expert so I'm not getting the whole picture.

If you want to get data from SQL and format it for your InfoPath form. There is probably an reference type that can be use to do that.

Usually we use either the SqlDataReader of SqlDataAdapter to do that:

SqlDataReader: msdn.microsoft.com/.../...lient.sqldatareader.aspx

SqlCommand command = new SqlCommand(queryString, connection);
connection.Open();
SqlDataReader reader = command.ExecuteReader();
// Call Read before accessing data.
while (reader.Read())
{
Console.WriteLine(String.Format("{0}, {1}",reader[0], reader[1]));
}
// Call Close when done reading.
reader.Close();

SqlDataAdapter: msdn.microsoft.com/.../...ient.sqldataadapter.aspx

SqlDataAdapter adapter = new SqlDataAdapter("SELECT * FROM Table1", myConn.Connection);
DataTable table = new DataTable()
adapter.Fill(table);

Regards,
Simon

Simon Deshaies Canada

3/23/2009 8:39:37 AM #

Eric Fleming

It is probably because I am not explaining it correctly that you may be misunderstanding.  I am looking for the simplest way to retrieve data from an SQL database table and present it to fields on an InfoPath form.  I can possibly use a basic 'Select * from <table> where <InfoPath field> is equal to <table field>.

I don't know if I need to use the SQLDataReader or SQLDataAdapter class to perform this function.

The fields on the InfoPath form are mapped directly to the fields in the SQL database table via the web service.  So for example the InfoPath field, (name1) is the actual field named, (name1) on the table.  I would wan to take the value in the InfoPath field, (name1) and use it's value to read the SQl database table, return the corresponding

The values to the mapped fields on the form.

Hopefully I am explaining what I am trying to do clearly enough so that I am not confusing you.

The basis of all of this is to populate an InfoPath form.

Thanks.

Eric Fleming United States

3/23/2009 2:58:25 PM #

Simon Deshaies

Eric,

Really at this point I can't answer any thing else then probably the SqlDataReader. It's more likely to be what you are looking for.

InfoPath is not a reference type it's a namespace. So, it can't be the return type of your method. It could be a array of String, a String, etc...

I suggest you ask your question on http://www.infopathdev.com it's the appropriate place for InfoPath questions as it's the official community forum.

Best of luck,

Simon

Simon Deshaies Canada

3/24/2009 4:35:45 AM #

Eric Fleming

I appreciate all that you have done.  I have stuck my foot in my mouth by using InfoPath and it is a whole different animal.  I was just looking for different ways I could go about building this functionality with InfoPath as the basis.

I still will be checking back here because you have excellent information on your site and I have used some of it.

Keep doing what you are doing.

Thanks.

Eric Fleming United States

3/26/2009 7:19:52 AM #

phoebe_ph



Dear Simon,

You're site is indeed so informative. Thank you so much for sharing your knowledge with everybody.
I am a newbie in programming and I find it overwhelming. I am trying to convert the ff. code below made of Powerbuilder (with an Oracle db connection) to C# please? I am wondering if you could help me with this? Thank you very much in advance for your help! and God Bless!



--------------------------------

String old_mrg, new_mrg

String  old_sns,  new_sns

Select  mrg_account, sns_number
into :old_mrg, :old_sns
from pub.subscription
where account = :his_acct;

If SQLCA.SQLCode = 0 then

Update pub.subscription
  set mrg_account = :mrg_acct,
    sns_number = :sns_acct
  where account = :his_acct;
commit;

If SQLCA.SQLCode = 0 then

  Select  mrg_account, sns_number
   into :new_mrg, :new_sns
   from pub.subscription
   where account = :his_acct;

  MessageBox('Change MRG account number',                &
       'Company account number: ' + string(his_acct) + '.~n' +       &
       '   Old -- MRG account: ' + old_mrg + '  SNS number: ' + old_sns + '.~n'+  &
       '   New -- MRG account: ' + new_mrg + '  SNS number: ' + new_sns + '.'    )
  return 'Update
Else
  return 'Error (' + string(SQLCA.SQLCode) +') on update.'
End If
Else
return 'Error (' + string(SQLCA.SQLCode) +') finding account# ' + string(his_acct) + '.'
End if

phoebe_ph United States

5/2/2009 7:55:21 AM #

Zakaria Khan

Hello Simon

Please can you assist with the following:

I have been using the SQL DataSource and the Binding Source to insert data and update table in my SQL database. Now I want to move to writing C# code to insert, select and update my sql table.

Please can you assist me.

Zakaria Khan South Africa

5/7/2009 1:57:24 AM #

Simon Deshaies

Hi phoebe_ph,

You can use the phoebe_ph www.developerfusion.com/.../ converter for your needs. I tried it but it says "line 1 col 1: EOF expected". You might what to have a look at it.

Otherwise to connect to Oracle with C#, I'm pretty sure there is an example on the oracle web site.

Thanks,

Simon

Simon Deshaies

5/7/2009 2:00:17 AM #

Simon Deshaies

Hi Zakaria,

I suggest you try out the sample, it should have every thing you need. If it's missing some thing please ask, I'll see what I can do.

Sample: weblog.simondeshaies.net/.../MySQLConnection.zip

Regards,

Simon

Simon Deshaies

5/11/2009 4:51:58 PM #

Joana

Hi Simon.
I was searching on Internet about how to build a class to handle my MS SQL Server connection in Visual C# form appl.
Can you please tell how do i build a class that void me to rewrite all the code every time i want access the database.

Resuming, that class allows me to connect to the database.

Im not very good in .net coding and im trying to learn it. Im now creating a database based application to store my costumers and workers and i need a class connection to manage database.

Hope the description helps you Smile
thank you very much anyway

Bye, kiss

Joana Portugal

7/8/2009 1:40:29 PM #

Michael George

I really like your class example and you have one of the most knowledgeable places around for what I am trying to accomplish. I am new to C# environment but here is what I would like to learn how to do and if willing work with you on creating.

in C#
What I would like is to have a class that is able to handle all my sql server needs.
It should take a sql connection string.
test if it is valid
Be able to preform 3 methods:
Method 1) Be given a select statement that will return a array or recordset
Method 2) Take a update statement
Method 3) Take a Insert Statement
Method 4) Take a Delete Statement

My problem in also in creating this is I am a little confused on how to create different types of methods and pass parameters in and receive values out of them... But I am learning. Smile

Michael George United States

10/18/2009 12:34:24 PM #

Richard Hetherington

I am a newbie C# programmer, and your information has taught me how to add / update SQL Tables.
I did a lot of searching and yours was the best written.   Thank you.

Richard Hetherington Canada

Powered by BlogEngine.NET
Theme by Mads Kristensen and Simon Deshaies

About the author

Simon Deshaies

Name of authorI do web development, I focus on your business processes by dramatically increasing your visibility. I develop strong Internet and Web applications. My main objective is to support your performance by optimizing your presence on the Web and to advise you on the best web technology to fit your needs.

Linked in profile

Specialties:
.NET development, Internet and Web applications.
HTML, XHTML, XML, XSL, CSS, ASP.NET, AJAX, C#, SQL.
Microsoft Windows Server 2000 to 2008, SQL Server 2000 to 2008, MySQL, IIS, DNS.

BlogRoll

Download OPML file OPML