Sql insert statement, how to generate a primary key?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • jsand03z
    New Member
    • Apr 2013
    • 5

    Sql insert statement, how to generate a primary key?

    Okay lets say I want to generate a primary key for organization_ID instead of manually entering it in a textbox I created.
    When this program runs the user is not suppose to see the primary key when submitting this information. Basically what I want is a random unique idenfier generated.

    My idea was to use some kind of count function?




    Code:
     Public Shared Function Insert_Organization() As DataSet
    
            Dim _DBConnector As New DBConnector()
            Dim ds As New DataSet
            Dim query As String
            Try
                query = "INSERT INTO Organization (Organization_Name, Organization_Info, Organization_Statistics, Organization_Total_Donated, Organization_ID) VALUES ('" & DataBaseProject_Hunger.AddOrganization.OrgNameTextBox.Text & "', '" & DataBaseProject_Hunger.AddOrganization.TextBox1.Text & "','" & DataBaseProject_Hunger.AddOrganization.TextBox2.Text & "','" & DataBaseProject_Hunger.AddOrganization.TextBox3.Text & "','" & DataBaseProject_Hunger.AddOrganization.TextBox4.Text & "' )"
                ds = _DBConnector.GetDataSet(query)
            Catch err As Exception
                MessageBox.Show(err.Message)
            Finally
                MsgBox("Added New Organization sucessfully.", MsgBoxStyle.Information, "")
            End Try
            Return ds
    Last edited by Rabbit; Apr 22 '13, 06:20 AM. Reason: Please use code tags when posting code.
  • r035198x
    MVP
    • Sep 2006
    • 13225

    #2
    Don't do it with your code. Let the database do it for you. How to make your database do it for you depends on which database you are using.

    Comment

    • jsand03z
      New Member
      • Apr 2013
      • 5

      #3
      Originally posted by r035198x
      Don't do it with your code. Let the database do it for you. How to make your database do it for you depends on which database you are using.
      I'm using sql server 2012. I tried it that way once and the program broke.

      Comment

      • vijay6
        New Member
        • Mar 2010
        • 158

        #4
        Hey jsand03z, if "Organization_I D" is an integer type then the simple way is set "Is Identity" to 'Yes' in your SQL Server 2012 database. Then don't insert value for "Organization_I D" column whenever you're inserting a new row in your table (The database will do it for you automatically).

        Comment

        • jsand03z
          New Member
          • Apr 2013
          • 5

          #5
          Thank you, it seems to work fine now.

          Comment

          Working...