Read data from sql database using datetime picker

前端 未结 5 1392
没有蜡笔的小新
没有蜡笔的小新 2021-01-16 15:29

How to read data from database using datetimepicker value. I have a datetimepicker and a datagridview in my form. I want to get data from Sql databse table with the selected

5条回答
  •  一整个雨季
    2021-01-16 16:18

    We see these questions here every day. They stems from the same problem.

    NEVER USE STRING CONCATENATION TO BUILD SQL QUERIES.

    It's a big problem. Of course you have already met the first effect. How to convert strings in an acceptable way to the effective data type? You need to solve parsing problems with embedded quotes, correct representation of dates and decimal numbers for the underlying database system. But the second and more subtle side effect of string concatenation is SQL Injection (This is just an instructive link because SQL Injection is a very large topic)

    To solve this kind of problems the only accepted way is to use PARAMETERS.
    This means that it is the database engine that solves in an efficient way the question, you need a string with parameter placeholders (the @something) and a collection of Parameters with the exact data type for the value of the parameter.

    So your code should change in this way

    Dim strSQL As String = "SELECT EMP_ID,EMP_NAME,AT_STATUS,AT_REMARK " + 
                           "FROM ATTENDANCE WHERE AT_DATE = @editdate " + 
                           "ORDER BY EMP_NAME ASC"
    Using con = new SqlConnection("constring_here")
        con.Open()
        Using cmd = new SqlCommand(strSQL, con)
            cmd.Parameters.AddWithValue("@editdate", DTPEDITAT.Value)
            ' do whatever you want with the command '
            ' like ExecuteReader or use a DataAdapter to fill datasets'
        End Using
    End Using
    

提交回复
热议问题