Click here to Skip to main content
15,921,841 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have a database called testDB and VStudio already connected and doing all INSERT, DELETE and UPDATE operations.

What I needed is whenever I add some department using new_dept_button_click" its automatically add "NOT AVAILABLE" text into dept_modified column on database.

Database Name = mydatabase
Table Name = dept_table
column Names = dept_id,dept_name,dept_created,dept_modified.

so I want to add "NOT AVAILABLE" text into 'dept_modified' when I add new department(new_dept_button_click).

So new department added the date of creation is showing but Im unable to get "NOT AVAILABLE" text in dept_modify since the department just created not modified.

Ty for understanding my bad English. hopefully i can make you understand.

Any luck for me?

DGV should looks like after adding new Department "TEST"

| ID | NAME | CREATED | MODIFIED |
------------------------------------------
| 1 | TEST | 2/16/2018 | N.A |
------------------------------------------

What I have tried:

Private Sub New_Department_Click(sender As Object, e As EventArgs) Handles
New_Department_Click.Click
        connection = New SqlConnection
        connection.ConnectionString = ("<MY CONNECTION STRING>")
        Dim reader As SqlDataReader
        Try
            connection.Open()
            Dim getDate As Date = Date.Now
            Dim addDate As String = getDate.ToString(" yyyy-MM-dd ")
            Dim query As String
            query = "INSERT into department(dept_id,dept_name,dept_created,dept_modified) values ('" & D_ID_box.Text & "','" & D_NAME_BOX.Text & "','" & addDate & "','"NOT AVAILABLE',ToString")"
            command = New SqlCommand(query, connection)
            reader = command.ExecuteReader
            MsgBox("Department added successfully")
            load_dgv()
            connection.Close()
        Catch ex As Exception
            MsgBox(ex.Message)
        Finally
            TextBox1.Text = String.Empty
            TextBox2.Text = String.Empty
            ComboBox1.Text = String.Empty
            connection.Dispose()
        End Try
    End Sub
Posted
Updated 20-Nov-20 3:02am
v3
Comments
Babai JermenKeller Sasmal 16-Feb-18 2:42am    
I tried the code you provided but it seems to like not working and giving same error "COVERSION FAILED WHEN CONVERTING DATE AND/OR TIME FROM CHARACTER STRING"

I tried to define the "Not Available/Modified" through using codes below,

Dim strText as String = "Not Modified"
query = "INSERT into department(dept_modified)" VALUES ('" & strText & "')
Richard Deeming 16-Feb-18 14:13pm    
Everything you wanted to know about SQL injection (but were afraid to ask) | Troy Hunt[^]
How can I explain SQL injection without technical jargon? | Information Security Stack Exchange[^]
Query Parameterization Cheat Sheet | OWASP[^]

Const query As String = "INSERT INTO department(dept_id, dept_name, dept_created, dept_modified) VALUES (@dept_id, @dept_name, @dept_created, @dept_modified)"

Using conn As SqlConnection = New SqlConnection("...")
    Using command As SqlCommand = New SqlCommand(query, conn)
        command.Parameters.AddWithValue("@dept_id", D_ID.box.Text)
        command.Parameters.AddWithValue("@dept_name", D_NAME_BOX.Text)
        command.Parameters.AddWithValue("@dept_created", strDate) ' NB: Don't store dates as strings!
        command.Parameters.AddWithValue("@dept_modified", "NOT MODIFIED")
        
        conn.Open()
        command.ExecuteNonQuery() ' NB: Don't use ExecuteReader when the query doesn't return anything!
    End Using
End Using

VB
query = "INSERT into department(dept_id,dept_name,dept_created,dept_modified) values ('" & D_ID_box.Text & "','" & D_NAME_BOX.Text & "','" & addDate & "','"NOT AVAILABLE',ToString")"

I suspect one of the last quotes to be wrong.

Not a solution to your question, but another problem you have.
Never build an SQL query by concatenating strings. Sooner or later, you will do it with user inputs, and this opens door to a vulnerability named "SQL injection", it is dangerous for your database and error prone.
A single quote in a name and your program crash. If a user input a name like "Brian O'Conner" can crash your app, it is an SQL injection vulnerability, and the crash is the least of the problems, a malicious user input and it is promoted to SQL commands with all credentials.
SQL injection - Wikipedia[^]
SQL Injection[^]
SQL Injection Attacks by Example[^]
PHP: SQL Injection - Manual[^]
SQL Injection Prevention Cheat Sheet - OWASP[^]
 
Share this answer
 
Comments
Babai JermenKeller Sasmal 16-Feb-18 2:52am    
its Giving error "END OF STATEMENT EXPECTED"
Babai JermenKeller Sasmal 16-Feb-18 4:26am    
This works for me..

all I need to change datatype from "date" to "nvarchar(10)" in sql database
This has been already partially answered, but I'd like to add a few points:

- As already said, you don't need to use ToString for a literal
SQL
... ,"NOT AVAILABLE")'

should be sufficient, although this could also be added as a default in the database if the value is always the same in the insert.

- More important than that is that never ever concatenate the input from the user as literal to the SQL statement. The only correct way is to use parameters in order to be safe from SQL injection and help with type conversions etc.

- Third thing is the usage of dispose or using. You should always dispose the disposable objects. I feel that the easiest way is to use using statements instead of calling the Dispose method. For example in your code you do not dispose the SqlCommand.

- Dates, never store the dates in any other format than in a date column. When using proper data types in the database it's easy to query, modify, calculate with the data. So instead of converting the date into a string, use a parameter and store DateTime.Now into it as-is.

- Dept_Id, not sure if this is the key and how it's supposed to be handled, but if this column is intended to be the actual primary key for the table, you probably should let the database to decide the value for it in order to prevent duplicates. If needed, have a look at IDENTITY columns for example

- The insert statement is executed by calling ExecuteReader. However, as this is an insert statement, nothing is expected to be returned from the database. A commonn practice is to use ExecuteNonQuery

If you have time, I'd suggest going through Properly executing database operations[^] . It explains the fundamentals for executing commands from different point of views.
 
Share this answer
 
v2
I re-coded the snippet you gave and formatted it a little better as well as removing some redundancies.

Here is how it would look without code included:
SQL
INSERT INTO department(dept_id, dept_name, dept_created, dept_modified) 
  VALUES ( "1", "Department Name", "2018-2-15", '"NOT AVAILABLE',ToString")

As you can tell, the "NOT AVAILABLE" would not be shown as a string (within Visual Studio) which leads to the errors I presume you have seen but not posted. By using Strings.Format method, as you can tell, the query becomes much more readable and easy to edit or updated. I also used the an object initializer (named With) when creating the SqlConnection. The code provided below should fix any problems you've had. Hope I helped!

VB
Dim conn As New SqlConnection() With { .ConnectionString = "<string>" }
Dim reader As SqlDataReader
Try
    conn.Open()
    Dim strDate As String = DateTime.Now.ToString("yyyy-MM-dd")
    Dim query As String = "INSERT INTO department(dept_id, dept_name, dept_created, dept_modified) VALUES ("
    query = query & String.Format("{0}, {1}, {2}, 'NOT MODIFIED')",
                                  D_ID.box.Text, D_NAME_BOX.Text, strDate)
    Dim command As new SqlCommand(query, conn)
    command.ExecuteReader()
    load_dgv()
    conn.Close()
Catch ex As Exception
    MessageBox.Show(ex.Message)
Finally
    TextBox1.Clear() : TextBox2.Clear() : TextBo3.Clear()
    ComboBox1.Text = String.Empty
    conn.Dispose()
    MessageBox.Show("Department added successfully.")
End Try
 
Share this answer
 
Comments
Richard Deeming 16-Feb-18 14:08pm    
Everything you wanted to know about SQL injection (but were afraid to ask) | Troy Hunt[^]
How can I explain SQL injection without technical jargon? | Information Security Stack Exchange[^]
Query Parameterization Cheat Sheet | OWASP[^]

Const query As String = "INSERT INTO department(dept_id, dept_name, dept_created, dept_modified) VALUES (@dept_id, @dept_name, @dept_created, 'NOT MODIFIED')"

Using conn As SqlConnection = New SqlConnection("...")
    Using command As SqlCommand = New SqlCommand(query, conn)
        command.Parameters.AddWithValue("@dept_id", D_ID.box.Text)
        command.Parameters.AddWithValue("@dept_name", D_NAME_BOX.Text)
        command.Parameters.AddWithValue("@dept_created", strDate) ' NB: Don't store dates as strings!
        
        conn.Open()
        command.ExecuteNonQuery() ' NB: Don't use ExecuteReader when the query doesn't return anything!
    End Using
End Using

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900