从字符串vb.net转换日期和/或时间时转换失败

时间:2017-08-31 12:16:10

标签: sql-server vb.net time-and-attendance

似乎找不到其他方法来转换它:

Label1.Text
来自员工数据库的

EmpIDcreate table Attendance ( EmpID varchar(25) foreign key references Employee(EmpID), remarks varchar (25) primary key not null, checkdate date, tin time, tout time, ) Button1.Text是Time In或Time Out(备注)

的状态

SQL Server出勤管理中的代码是:

if profit > 0:
    print('After the transaction, you lost ' ,profit, ' dollars.')
elif profit < 0:
    print('After the transaction, you gained ' ,profit, ' dollars.')

1 个答案:

答案 0 :(得分:1)

编写/运行数据库查询是一种可怕的方法。基本上发生的事情是,在组装SQL字符串时,您的日期值将被Visual Basic转换为字符串表示形式,但sql-server无法将生成的字符串转换回日期

幸运的是,它没有,你应该专门编写你的查询,以便它不必

看起来应该更像这样:

Dim sqlC as New SqlCommand("INSERT INTO attendance VALUES(@emp, @rem, @dat, @tin, null)", myConnectionStringVariable)
sqlC.Parameters.AddWithValue("emp", Label1.Text)
sqlC.Parameters.AddWithValue("rem", Button1.Text)
sqlC.Parameters.AddWithValue("dat", Date.Today)
sqlC.Parameters.AddWithValue("tin", DateTime.Now)

请至少查看有关参数化查询的一些教程。从来没有(曾经)再次编写一个SQL,其中您希望在SQL中包含的值(来自某个UI组件)是字符串连接到SQL命令字符串

更好的是,停止在按钮单击事件处理程序中编写SQL代码,并使用ORM库(数据集,实体框架,nhibernate等)

您的代码原样,是一个巨大的安全风险,并且是一种完全避免的模式