I write a sql statement into vb.net to fetch data from msaccess where date equal to patepicker control. But here syntax error.
My code given below:-
Dim ct As String = "select * from add_student where _Date <= #" & dtDate1.ToString("MM/dd/yyyy") & "#"
cmd = New OleDbCommand(ct)
cmd.Connection = con
rdr = cmd.ExecuteReader()
Note:- _Date column had Date/Time Data type in ms access database
Please suggest me, Where is mistake
You should always use parameters:
dim sqlQuery ="Select * from add_student where _Date = ?"
using conn = New OleDbConnection("connectionstring")
conn.open()
Using selectCmd As New OleDbCommand(sqlQuery, conn)
selectCmd.Parameters.Add("_Date", OleDbType.Date).Value = dtDate1
using rdr = selectCmd.ExecuteReader()
while rdr.read()
End While
End Using
End Using
End Using
Your issue may be that "/" is not a slash but the localized date separator.
Thus, force slashes:
Dim ct As String = "select * from add_student where _Date <= #" & dtDate1.ToString("MM'/'dd'/'yyyy") & "#"
and perhaps brackets for the weird field name:
Dim ct As String = "select * from add_student where [_Date] <= #" & dtDate1.ToString("MM'/'dd'/'yyyy") & "#"
Related
when iam trying to write this select in vb.net and sqlserver database:
da = New SqlDataAdapter("select * from UserComeView where ( ComeUserFullName=" & cmb_user.SelectedValue & " ) and ( ComeDate between '" & Date1.Value & "' and '" & Date2.Value & "')", sql.sqlcon)
comes this error:
Conversion failed when converting date and/or time from character
string.
I will assume that ComeDate is some type of Date field. I altered your Select command to include parameters. Defining the datatype in the .Add method should clear up your conversion problem. I had to guess at the datatype. Check the datatype in your database. Then pass the command, which includes the connection, to the constructor of the DataAdapter.
Private Sub OpCode()
Dim dt As New DataTable
Using cn As New SqlConnection("Your connection string"),
cmd As New SqlCommand("Select * From UserComeView Where ComeUserFullName = #FullName And ComeDate Between #Date1 And #Date2;", cn)
cmd.Parameters.Add("#FullName", SqlDbType.NVarChar, 200).Value = cmb_user.SelectedValue
cmd.Parameters.Add("#Date1", SqlDbType.Date).Value = Date1.Value
cmd.Parameters.Add("#Date2", SqlDbType.Date).Value = Date2.Value
Using da As New SqlDataAdapter(cmd)
da.Fill(dt)
End Using
End Using
DataGridView1.DataSource = dt
End Sub
I am using the following SQL statement :
Dim strSql5 As String = "SELECT * FROM dbo.ontledings " & _
" where plaasblok = #plaasblokparsversoeke " & _
" and analisedatum = #laastedatum"
cnn.Open()
Dim aksie2 As New SqlClient.SqlCommand(strSql5, cnn)
aksie2.Parameters.Add("#plaasblokparsversoeke", SqlDbType.VarChar).Value = plaasblokparsversoeke
aksie2.Parameters.Add("#laastedatum", SqlDbType.Date).Value = laastedatum
aksie2.ExecuteNonQuery()
cnn.Close()
I want to fill a datatable like so :
Dim dtb5 As New DataTable
dtb5.Clear()
Using cnn As New SqlConnection("Data Source=GIDEON-E-LAPTOP\SQLEXPRESS2014;Initial Catalog=SkeduleringDatabasis;Integrated Security=True")
cnn.Open()
Using dad5 As New SqlDataAdapter(strSql5, cnn)
dad5.Fill(dtb5)
End Using
cnn.Close()
End Using
I get the following error message : Must declare the scalar variable "#plaasblokparsversoeke"
I cannot figure out where and how to declare the scalar variables.
The error occurs at the line : dad5.Fill(dtb5)
Regards
You need to add the parameters like
cmd.Parameters.Clear()
cmd.Parameters.AddWithValue("#plaasblokparsversoeke", plaasblokparsversoeke.Text)
cmd.Parameters.AddWithValue("#laastedatum", laastedatum.Text)
As correctly commented below, you need to use the Add method to add the paramters:
cmd.Parameters.Add("#plaasblokparsversoeke", SqlDbType.Varchar).Value = plaasblokparsversoekeVariable;
cmd.Parameters.Add("#laastedatum", SqlDbType.Varchar).Value = laastedatumVariable;
Firstly, avoid hard-coding a parameterised query in this way, for avoidance of SQL injection.
To answer your specific question: you are trying to use parameters in the query without having defined them in the SQLCommand.
Have a look at MSDN for the full documentation.
With this query
Dim strSql5 As String = "SELECT * FROM dbo.ontledings " & _
" where plaasblok = #plaasblokparsversoeke " & _
" and analisedatum = #laastedatum"
You are definining 2 SQL variables called #plaasblokparsversoeke and #laastedatum that you have to pass as parameters to your command, like this
command.Parameters.Add("#plaasblokparsversoeke", SqlDbType.Int);
command.Parameters["#plaasblokparsversoeke "].Value = yourValue;
MSDN article on SQL command parameters here
I should change all queries to use parameters to protect app from SQL injection.
Current insert sample which works is:
If Len(ExecuteQuery("INSERT INTO ICE_Order_Details(Order_ID, Product_ID, License_Type_ID, Maintenance_ID, Qty, Shareit_Running_No, Price, Total) VALUES(" & OrderID & ", " & ProductID & ", " & LicenseTypeID & ", " & MaintenanceID & ", " & Val(Request("QUANTITY")) & ", " & Val(Request("RUNNING_NO")) & ", " & Price & ", " & Price * Val(Request("QUANTITY")) & ")")) > 0 Then
'SendBadRequest "Could not run insert Order detail query"
Can you help me to write parametric query instead of this?
I tried a lot of ways to do this but here is below last one.
Dim ConnString As New SqlConnection("Provider=SQLOLEDB.0;Data Source=something;Initial Catalog=something;Persist Security Info=True;User ID=something;Password=something")
Dim SqlString As String ="INSERT INTO ICE_Order_Details(Order_ID, Product_ID, License_Type_ID, Maintenance_ID, Qty, Shareit_Running_No, Price, Total) VALUES(#OrderID, #ProductID, #LicenseTypeID, #MaintenanceID, #Qty, #RunningNo, #Price, #Total)"
Using conn As New OleDbConnection(ConnString)
Using cmd As New OleDbCommand(SqlString, conn)
cmd.CommandType = CommandType.Text
cmd.Parameters.AddWithValue("#OrderID", OrderID)
cmd.Parameters.AddWithValue("#ProductID", ProductID)
cmd.Parameters.AddWithValue("#LicenseTypeID", LicenseTypeID)
cmd.Parameters.AddWithValue("#MaintenanceID", MaintenanceID)
cmd.Parameters.AddWithValue("#Qty", Val(Request("QUANTITY")))
cmd.Parameters.AddWithValue("#RunningNo", Val(Request("RUNNING_NO")))
cmd.Parameters.AddWithValue("#Price", Price)
cmd.Parameters.AddWithValue("#Total", Price * Val(Request("QUANTITY")))
conn.Open()
cmd.ExecuteNonQuery()
End Using
End Using
Edit: It still doesn't work. Here is my current code for adding parameters:
cmd.Parameters.Add("#OrderID", SqlDbType.Int).Value = OrderId
cmd.Parameters.Add("#ProductID", SqlDbType.Int).Value = ProductID
cmd.Parameters.Add("#LicenseTypeID", SqlDbType.Int).Value = LicenseTypeID
cmd.Parameters.Add("#MaintenanceID", SqlDbType.Int).Value = MaintenanceID
cmd.Parameters.Add("#Qty", SqlDbType.Int).Value = Int32.Parse(Request("QUANTITY"))
cmd.Parameters.Add("#RunningNo", SqlDbType.Int).Value = Int32.Parse(Request("RUNNING_NO"))
cmd.Parameters.Add("#Price", SqlDbType.Money).Value = Money.Parse(Price)
cmd.Parameters.Add("#Total", SqlDbType.Money).Value = Money.Parse(Price * Int32.Parse(Request("QUANTITY")))
Edit: I changed my insert query to test only insert with parameters. But it don't work
Dim ConnString As String = ConfigurationManager.ConnectionStrings("DB_Connection_String0").ConnectionString
Dim SqlString As String ="INSERT INTO Unsubscribed(E-Mail) VALUES(#E-Mail)"
Using conn As New OleDbConnection(ConnString)
Using cmd As New OleDbCommand(SqlString, conn)
cmd.CommandType = CommandType.Text
cmd.Parameters.Add("#E-Mail", SqlDbType.nvarchar).Value = "testiram#obrisime.sada"
conn.Open()
cmd.ExecuteNonQuery()
End Using
End Using
here is error which i got (it marked 'As') if I change connection string it show error on next 'As' in code with same error message
Microsoft VBScript compilation error '800a0401'
Expected end of statement
/Test.asp, line 8
Dim ConnString As String =
ConfigurationManager.ConnectionStrings("DB_Connection_String0").ConnectionString
---------------^
Finally I found solution for this
Thanks all for help!
here is code below which work fine
<%
Dim oConn, oCmd, ds, sql
p1 = "test"
p2 = "test"
p3 = "test"
ds = "Provider=SQLOLEDB.1;Data Source=___;Initial Catalog=___;User ID=___;Password=___;"
sql = "INSERT INTO table (prop1, prop2, prop3) VALUES (?,?,?)"
Set oConn=Server.CreateObject("ADODB.Connection")
oConn.Open ds
Set oCmd = Server.CreateObject("ADODB.Command")
oCmd.ActiveConnection = oConn
oCmd.CommandText = sql
oCmd.CommandType = 1
oCmd.Parameters(0) = p1
oCmd.Parameters(1) = p2
oCmd.Parameters(2) = p3
oCmd.Execute()
oConn.close
Set oConn=nothing
%>
it is better to use sqlhelper class file by microsoft which i think is best for this cause and is relatively easy to use and shortens code by much. e.g
in save click event it will go like this
sqlParameter[] parem=
{
new sqlparameter("#value1"urcontrol.text),
new sqlparameter("#value2"urcontrol.text),
new sqlparameter("#value3"urcontrol.text)
};
sqlhelper.executenonquery (connectionstring,commandtype.storeprocedure,"ProcedureName",parem);
rest will be handled automatically by sqlhelper class file
There are 10 rows in primary_student_table.
When I execute the following code, the result was -1.
Dim count As Int16
con.Open()
query = "SELECT COUNT(roll) AS rollcount FROM primary_student_table WHERE admityear = 2011 AND batch = 1 "
cmd = New SqlCommand(query, con)
count = cmd.ExecuteNonQuery
MsgBox(count)
con.Close()
What's the problem in the above code?
You should be using ExecuteScalar() rather than ExecuteNonQuery() because you are fetching a value.
count = Convert.ToInt16(cmd.ExecuteScalar())
MsgBox(count.ToString())
SqlCommand.ExecuteScalar Method
For proper coding
use using statement for proper object disposal
use try-catch block to properly handle exceptions
Example Code:
Dim connStr As String = "connection string here"
Dim query As String = "SELECT COUNT(roll) AS rollcount FROM primary_student_table WHERE admityear = 2011 AND batch = 1"
Using conn As New SqlConnection(connStr)
Using cmd As New SqlCommand()
With cmd
.Connection = conn
.CommandText = query
.CommandType = CommandType.Text
End With
Try
conn.Open()
Dim count As Int16 = Convert.ToInt16(cmd.ExecuteScalar())
MsgBox(count.ToString())
Catch(ex As SqlException)
' put your exception here '
End Try
End Using
End Using
The solution is to replace
count = cmd.ExecuteNonQuery
with
count = cmd.ExecuteScalar
Like Robert Beaubien said in his comments
MysqlConn = New MySqlConnection
MysqlConn.ConnectionString = "server=localhost;userid=root;password=1234;database=dblms"
Dim READER As MySqlDataReader
Try
MysqlConn.Open()
Dim Query As String
Query = "Select * from dblms.accounts"
COMMAND = New MySqlCommand(Query, MysqlConn)
READER = COMMAND.ExecuteReader
Dim count As Integer
count = 0
While READER.Read
count = count + 1
End While
MysqlConn.Close()
Catch ex As MySqlException
MessageBox.Show(ex.Message)
Finally
MysqlConn.Dispose()
End Try
the value in count will be the number of rows in a table :) hope this helped
Is there a way to use DateTimePicker as your searching device for ListView?
I don't know how to use DateTimePicker as my search engine...
HERE IS THE CODES FOR MY SEARCH:
Dim conn As SqlConnection
Dim cmd As SqlCommand
Dim da As SqlDataAdapter
Dim ds As DataSet
Dim itemcoll(100) As String
Me.ListView1.View = View.Details
Me.ListView1.GridLines = True
ListView1.Items.Clear()
conn = New SqlConnection("Data Source=#####;Initial Catalog=#####;Persist Security Info=True;User ID=#####;Password=#####")
Dim strQ As String = String.Empty
strQ = "SELECT ControlNo,EmpNo,CheckOutDate,CheckOutTime,TaxiNo,PlateNo,Model,Make FROM dbo.ChkInOut WHERE ControlNo ='" + txtsearch.Text + "'"
cmd = New SqlCommand(strQ, conn)
da = New SqlDataAdapter(cmd)
ds = New DataSet
da.Fill(ds, "Table")
Dim i As Integer = 0
Dim j As Integer = 0
For i = 0 To ds.Tables(0).Rows.Count - 1
For j = 0 To ds.Tables(0).Columns.Count - 1
itemcoll(j) = ds.Tables(0).Rows(i)(j).ToString()
Next
Dim lvi As New ListViewItem(itemcoll)
Me.ListView1.Items.Add(lvi)
Next
There are few problems with your code as is, so let's take them one at a time
SqlCommand inherits from DbCommand, which implements the IDisposable interface.
The primary use of this interface is to release unmanaged resources.
The best way do that is with the Using keyword. For a code example of that, take a look at the sample code at the bottom of this page.
Same goes for SqlConnection, wrap it in a Using statement.
Don't concatenate strings together to make SQL queries, this opens your application up to SQL Injection attacks. There are examples of how to create parameterized queries here and here (unfortunately I didn't see a good example on MSDN).
In your case, the query will look like this:
strQ = "SELECT ControlNo, ..<rest of columns>.. ,Model,Make " & _
"FROM dbo.ChkInOut " & _
"WHERE ControlNo = #controlNo"
cmd = New SqlCommand(strQ, conn)
cmd.Parameters.AddWidthValue("#controlNo", txtsearch.Text);
... rest of code here ...
To query by a user specified date, you need to first get the date from the DateTimePicker.Value property. Then construct a query (like in the example above) and pass a parameter with the selected date. You may find this question abou SQL Server dates helpful.