vb.net 如何避免错误:“CommandText 属性尚未正确初始化”?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20799330/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to avoid error: "CommandText property has not been initialized properly"?
提问by firefly
database is in the sqlYog,
数据库在 sqlYog 中,
when i run this program i am getting the error:
CommandText property has not been initialized properly..?
当我运行这个程序时,我收到错误:
CommandText 属性尚未正确初始化..?
please help me
请帮我
Imports MySql.Data.MySqlClient
Imports System.Data
Partial Class login
Inherits System.Web.UI.Page
Public dbconn As New MySqlConnection
Public sql As String
Public dbcomm As New MySqlCommand
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
dbconn = New MySqlConnection("data source= localhost; user id=root; password=search; database=bookstore;")
dbconn.Open()
dbcomm.Connection = dbconn
End Sub
Protected Sub btn_login_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btn_login.Click
Try
dbcomm = New MySqlCommand(sql, dbconn)
sql = "select * from bookstore.lib_user where username=@username and password=@password"
dbcomm.Parameters.AddWithValue("@username", txt_username.Text)
dbcomm.Parameters.AddWithValue("@password", txt_password.Text)
Dim dbadpt As New MySqlDataAdapter(dbcomm)
Dim dt As New DataTable()
dbadpt.Fill(dt)
If dt.Rows.Count > 0 Then
MsgBox("login is suceesfull")
Else
Literal1.Text = "invalid login"
End If
Catch ex As Exception
MsgBox("read this error: " + ex.Message)
End Try
End Sub
End Class
回答by Sain Pradeep
Please change the sequence of lines.
请更改行的顺序。
First set the query text then call the command constructor.
首先设置查询文本然后调用命令构造函数。
sql = "select * from bookstore.lib_user where username=@username and password=@password"
dbcomm = New MySqlCommand(sql, dbconn)
回答by Suraj Singh
As per your code sqlis empty when assigning to your MySqlCommand, You need to set the sqlvalue first then assign it to your MySqlCommandobject .
根据您的代码sql在分配给您时为空MySqlCommand,您需要先设置sql值,然后将其分配给您的MySqlCommand对象。
sql = "select * from bookstore.lib_user where username=@username and password=@password"
dbcomm = New MySqlCommand(sql, dbconn)

