2011年6月18日 星期六

在SQL的datetime字段中使用Null值

方法(1)
Dim sqlStmt As String
Dim conString As String
Dim cn As SqlConnection
Dim cmd As SqlCommand
Dim sqldatenull As SqlDateTime
Try
sqlStmt = "insert into Emp (FirstName,LastName,Date) Values (@FirstName,@LastName,@Date) "
conString = "server=localhost;database=Northwind;uid=sa;pwd=;"
cn = New SqlConnection(conString)
cmd = New SqlCommand(sqlStmt, cn)

cmd.Parameters.Add(New SqlParameter("@FirstName", SqlDbType.NVarChar, 11))
cmd.Parameters.Add(New SqlParameter("@LastName", SqlDbType.NVarChar, 40))
cmd.Parameters.Add(New SqlParameter("@Date", SqlDbType.DateTime))

sqldatenull = SqlDateTime.Null

cmd.Parameters("@FirstName").Value = txtFirstName.Text
cmd.Parameters("@LastName").Value = txtLastName.Text
If (txtDate.Text = "") Then
cmd.Parameters("@Date").Value = sqldatenull
'cmd.Parameters("@Date").Value = DBNull.Value
Else
cmd.Parameters("@Date").Value = DateTime.Parse(txtDate.Text)
End If
cn.Open()
cmd.ExecuteNonQuery()
Label1.Text = "Record Inserted Succesfully"

Catch ex As Exception
Label1.Text = ex.Message
Finally
cn.Close()
End Try

方法(2)
Dim sqlStmt As String
Dim conString As String
Dim cn As OleDbConnection
Dim cmd As OleDbCommand
Try
sqlStmt = "insert into Emp (FirstName,LastName,Date) Values (?,?,?) "
conString = "Provider=sqloledb.1;user id=sa;pwd=;database=northwind;data source=localhost"
cn = New OleDbConnection(conString)
cmd = New OleDbCommand(sqlStmt, cn)

cmd.Parameters.Add(New OleDbParameter("@FirstName", OleDbType.VarChar, 40))
cmd.Parameters.Add(New OleDbParameter("@LastName", OleDbType.VarChar, 40))
cmd.Parameters.Add(New OleDbParameter("@Date", OleDbType.Date))

cmd.Parameters("@FirstName").Value = txtFirstName.Text
cmd.Parameters("@LastName").Value = txtLastName.Text
If (txtDate.Text = "") Then
cmd.Parameters("@Date").Value = DBNull.Value
Else
cmd.Parameters("@Date").Value = DateTime.Parse(txtDate.Text)
End If
cn.Open()
cmd.ExecuteNonQuery()
Label1.Text = "Record Inserted Succesfully"

Catch ex As Exception
Label1.Text = ex.Message
Finally
cn.Close()
End Try

沒有留言:

張貼留言