I want to put data in SQL table through vb.net in two columns which are Txn_Amount and Post_Amount
where textbox3 = Txn_Amount
Post Amount = Textbox4 - textbox3
but I want if textbox4 = "" than Post amount should be 0
This is my code:
Call Get_TxnID()
Dim Txn_Amount As String = TextBox3.Text
Dim Post_Amount As String = Val(TextBox4.Text) - Val(TextBox3.Text)
Dim query As String = "Insert into Txn_Master values (#Txn_Amount, #Post_Amount)"
Using cmd As New SqlCommand(query, Connection)
cmd.Parameters.AddWithValue("Txn_Amount", Txn_Amount)
cmd.Parameters.AddWithValue("Post_Amount", Post_Amount)
Connection.Open()
cmd.ExecuteNonQuery()
Connection.Close()
End Using
MsgBox("Transaction Success", MsgBoxStyle.Information)
It work well when i have value in both boxes For example :- textbox3.text = 25000 and textbox4.text = 50000 then Post_Amount is 25000
but if textbox3.text = 25000 and textbox4.text = "" then it shows -25000 in post_amount but i want if textbox4 = "" then post amount should be "" or "0"
I have tried
Dim Txn_Amount As String = TextBox3.Text
If textbox4.text="" then
Dim Post_Amount As String = ""
Else
Dim Post_Amount As String = Val(TextBox4.Text) - Val(TextBox3.Text)
endif
Dim query As String = "Insert into Txn_Master values (#Txn_Amount, #Post_Amount)"
Using cmd As New SqlCommand(query, Connection)
cmd.Parameters.AddWithValue("Txn_Amount", Txn_Amount)
cmd.Parameters.AddWithValue("Post_Amount", Post_Amount)
Connection.Open()
cmd.ExecuteNonQuery()
Connection.Close()
End Using
MsgBox("Transaction Success", MsgBoxStyle.Information)
But it is now working, please help me with this
If you initialise a variable for "Post_Amount" to zero, then you can check if the appropriate TextBox has an entry before setting its value, something like this:
Dim txnAmount As Integer = 0
If Not Integer.TryParse(tbTxnAmount.Text, txnAmount) Then
' Prompt user to enter an appropriate value in the TextBox.
' Exit Sub
End If
Dim postAmount As Integer = 0
'TODO Use sensible names for tbAmountA and tbAmountB.
If Not String.IsNullOrWhiteSpace(tbAmountB.Text) Then
'TODO: Use sensible names for these variables.
Dim a = 0
Dim b = 0
If Integer.TryParse(tbAmountA.Text, a) AndAlso Integer.TryParse(tbAmountB.Text, b) Then
postAmount = b - a
End If
End If
Using conn As New SqlConnection("your connection string")
Dim sql = "INSERT INTO [Txn_Master] VALUES (#Txn_Amount, #Post_Amount)"
Using cmd As New SqlCommand(sql, conn)
cmd.Parameters.Add(New SqlParameter With {.ParameterName = "#Txn_Amount",
.SqlDbType = SqlDbType.Int,
.Value = txnAmount})
cmd.Parameters.Add(New SqlParameter With {.ParameterName = "#Post_Amount",
.SqlDbType = SqlDbType.Int,
.Value = postAmount})
conn.Open()
cmd.ExecuteNonQuery()
cmd.Clone()
End Using
End Using
I strongly recommend that you use meaningful names for the TextBoxes and variables. "tbAmountB" is your "TextBox4", but it still needs a better name.
Strictly speaking, it doesn't need the String.IsNullOrWhiteSpace test as such a string would fail the parsing, but it does leave the intent clear.
Also, to make your code easier for others to read, it is convention to use camelCase for variable names: Capitalization Conventions.
Related
I get this error when I run the code. The records are inserted into the table, but the program stops at the error.
The parameterized query '(#EmpName varchar(8000),#USDBasic varchar(8000),#OtherUSDEarning' expects the parameter '#EmpName', which was not supplied.
Code:
Dim connetionString As String
Dim cnn As SqlConnection
connetionString = "Data Source=Server\SQlExpress;Initial Catalog=CreSolDemo;User ID=sa;Password=Mkwn#011255"
cnn = New SqlConnection(connetionString)
If DataGridView1.Rows.Count > 0 Then
Dim cmd As New Data.SqlClient.SqlCommand
cmd.CommandText = " INSERT INTO TempPeriodTrans (EmpName, USDBasic, OtherUSDEarnings, ZDollarBasic, OtherZDEarnings) VALUES (#EmpName, #USDBasic, #otherUSDEarnings, #ZDollarBasic, #OtherZDEarnings) "
cmd.Parameters.Add("#EmpName", SqlDbType.VarChar)
cmd.Parameters.Add("#USDBasic", SqlDbType.VarChar)
cmd.Parameters.Add("#OtherUSDEarnings", SqlDbType.VarChar)
cmd.Parameters.Add("#ZDollarBasic", SqlDbType.VarChar)
cmd.Parameters.Add("#OtherZDEarnings", SqlDbType.VarChar)
cmd.Connection = cnn
cnn.Open()
For i As Integer = 0 To DataGridView1.Rows.Count - 1
cmd.Parameters(0).Value = DataGridView1.Rows(i).Cells(0).Value
cmd.Parameters(1).Value = DataGridView1.Rows(i).Cells(1).Value
cmd.Parameters(2).Value = DataGridView1.Rows(i).Cells(2).Value
cmd.Parameters(3).Value = DataGridView1.Rows(i).Cells(3).Value
cmd.Parameters(4).Value = DataGridView1.Rows(i).Cells(4).Value
cmd.ExecuteNonQuery()
Next
cnn.Close()
End If
MsgBox("Record saved")
End Sub
There seem to be a few things here.
As a rule, any time you open a connection to your data base it should be wrapped in a Using block so that that connection gets closed and disposed before you exit that block
You have a lot of params that are being set as SqlDbType.varchar where you should probably have other types. (SqlDbType.Money in particular)
When you are working with sqlcommand, it is worth wrapping it in a using block as well and creating a new one as you need it.
There is some memory to it where it will try not to reuse parameters in subsequent queries. Instead of just changing the value of the param, throw that sqlCommand in the trash bin each time and grab a new one. This is where I believe your problem is. I moved the sqlcommand creation into your loop and declare the values in-line below.
Also, protip, avoid including your actual password in the connetion string on Stack Overflow
Dim connectionString As String = "yourConnectionString"
Using cnn As new SqlConnection(connectionString)
cnn.Open()
For Each row in DataGridView1.Rows
Using cmd As New Data.SqlClient.SqlCommand("INSERT INTO TempPeriodTrans (EmpName, USDBasic, OtherUSDEarnings, ZDollarBasic, OtherZDEarnings) Values (#EmpName, #USDBasic, #otherUSDEarnings, #ZDollarBasic, #OtherZDEarnings) ", cnn)
cmd.Parameters.Add("#EmpName", SqlDbType.VarChar).value = row.Cells(0).Value
cmd.Parameters.Add("#USDBasic", SqlDbType.VarChar).value = row.Cells(1).Value
cmd.Parameters.Add("#OtherUSDEarnings", SqlDbType.VarChar).value = row.Cells(2).Value
cmd.Parameters.Add("#ZDollarBasic", SqlDbType.VarChar).value = row.Cells(3).Value
cmd.Parameters.Add("#OtherZDEarnings", SqlDbType.VarChar).value = row.Cells(4).Value
cmd.ExecuteNonQuery()
End using
Next
End using
MsgBox("Record Saved")
End Sub
I'm currently working on my project for which I used VB.NET 2019 and SQL server. I need to create a function which auto generates IDs.
I want my IDs to be like these: P001, P002, P003 etc. Can someone show me how to code it? Below is my code
Private Sub Form4_Load_1(sender As Object, e As EventArgs) Handles MyBase.Load
BindData()
Dim data As String = "Data Source=LAPTOP-M8KKSG0I;Initial Catalog=Oceania;Integrated Security=True"
Dim con As New SqlConnection(data)
Try
If Con.State = ConnectionState.Closed Then
con.Open()
End If
Dim sql As String = "Select Max(PatientID) from Patient"
Dim cmd As New SqlCommand(sql, con)
Dim Max As String = cmd.ExecuteScalar
If Max > 0 Then
TextBox1.Text = Max + 1
Else
TextBox1.Text = "P01"
End If
Catch ex As Exception
MsgBox(Err.Description)
End Try
End Sub
You can try like this. Here 1 is an auto-generated number that may be an identity key column value from a table in SQL Server.
Dim number As Integer = 1
Dim numberText As String = "P" & number.ToString().PadLeft(3, "0")
Live demo
You can add a computed column like this in your table for auto-generating the sequences. This will reduce the chances of duplicate value runtime once more than one person will do the entry simultaneously.
Alter table Patient ADD PatientCode AS ('P' + Convert(Varchar(3),CONCAT(REPLICATE('0', 3 - LEN(PatientID)), PatientID)) )
To get the column value dynamically you can try the below code to generate function.
Private Sub GenerateSequnce()
Dim constring As String = "Data Source=TestServer;Initial Catalog=TestDB;User id = TestUser;password=test#123"
Using con As New SqlConnection(constring)
Using cmd As New SqlCommand("Select Top 1 ISNULL(TaxCode, 0) from Tax_Mst Order By TaxCode Desc", con)
cmd.CommandType = CommandType.Text
Using sda As New SqlDataAdapter(cmd)
Using dt As New DataTable()
sda.Fill(dt)
Dim maxNumberCode = dt.Rows(0)("TaxCode").ToString()
If (maxNumberCode = "0") Then
maxNumberCode = "1"
End If
Dim numberText As String = "P" & maxNumberCode.ToString().PadLeft(3, "0")
End Using
End Using
End Using
End Using
End Sub
Here the column TaxCode is int with identity constraint.
With the minor correction in your code, you can achieve this as shown below.
Dim data As String = "Data Source=LAPTOP-M8KKSG0I;Initial Catalog=Oceania;Integrated Security=True"
Dim con As New SqlConnection(data)
Try
If con.State = ConnectionState.Closed Then
con.Open()
End If
Dim sql As String = "Select ISNULL(Max(PatientID), 0) from Patient"
Dim cmd As New SqlCommand(sql, con)
Dim Max As String = cmd.ExecuteScalar
If (Max = "0") Then
Max = "1"
Else
Max = CInt(Max) + 1
End If
Dim numberText As String = "P" & Max.ToString().PadLeft(3, "0")
TextBox1.Text = numberText
Catch ex As Exception
MsgBox(Err.Description)
End Try
OUTPUT
This is how I set up my command. It stops with the first parameter, UpdateType. This code is being updated from VB.NET 2008 version.
Dim db As New DB()
Dim cmd As SqlCommand = New SqlCommand()
'Put into an object, and use AddWithValue due to Parameters.Add being deprecated.
Dim UpdateType As String = "PARAMETERS"
If IsNewJob Then
cmd.CommandText = "sp_MB_AddJob"
Else
cmd.CommandText = "sp_MB_UpdateJob"
cmd.Parameters.AddWithValue("#UpdateType", SqlDbType.NVarChar).Value = UpdateType
cmd.Parameters.AddWithValue("#OrigJobName", OrigJobName.ToString)
End If
cmd.Parameters.AddWithValue("#UserID", CInt(Utils.GetLoggedInUserID))
cmd.Parameters.AddWithValue("#ProjectName", ProjectName.ToString)
You should use .Add instead with the type and for NVARCHAR, VARCHAR, or VARBINARY
with the length. Here I show how to do the tings you have in the question, I made up lengths just for the example. Using AddWithValue can have negative impact on SQL performance and other things.
Some information to help you can be found in many places including here https://learn.microsoft.com/en-us/dotnet/framework/data/adonet/configuring-parameters-and-parameter-data-types
Dim db As New DB()
Dim cmd As SqlCommand = New SqlCommand()
Dim UpdateType As String = "PARAMETERS"
cmd.CommandType = CommandType.StoredProcedure
If IsNewJob Then
cmd.CommandText = "sp_MB_AddJob"
Else
cmd.CommandText = "sp_MB_UpdateJob"
cmd.Parameters.Add("#UpdateType", SqlDbType.NVarChar, 10).Value = UpdateType
cmd.Parameters.Add("#OrigJobName", SqlDbType.NVarChar, 50).Value = OrigJobName.ToString
End If
cmd.Parameters.Add("#UserID", SqlDbType.Int).Value = CInt(Utils.GetLoggedInUserID)
cmd.Parameters.Add("#ProjectName", SqlDbType.NVarChar, 30).Value = ProjectName.ToString
Keep your database objects local to the method where they are used so you can control that they are closed and disposed. `Using...End Using blocks take care of this for you. Note a single Using block is handling both the connection and the command.
The .Add method is NOT being deprecated. What is obsolute is the .Add(String, Object) overload. `.AddWithValue is certainly out of favor. See http://www.dbdelta.com/addwithvalue-is-evil/
and
https://blogs.msmvps.com/jcoehoorn/blog/2014/05/12/can-we-stop-using-addwithvalue-already/
and another one:
https://dba.stackexchange.com/questions/195937/addwithvalue-performance-and-plan-cache-implications
Here is another
https://andrevdm.blogspot.com/2010/12/parameterised-queriesdont-use.html
I had to guess at the datatype and column size of your parameters. Check your database for the actual values and correct the code accordingly.
Private Sub OpCode()
Dim UpdateType As String = "PARAMETERS"
Using cn As New SqlConnection("Your connection string"),
cmd As New SqlCommand()
cmd.Connection = cn
If IsNewJob Then
cmd.CommandText = "sp_MB_AddJob"
Else
cmd.CommandText = "sp_MB_UpdateJob"
cmd.Parameters.Add("#UpdateType", SqlDbType.NVarChar, 50).Value = UpdateType
cmd.Parameters.Add("#OrigJobName", SqlDbType.NVarChar, 200).Value = OrigJobName.ToString
End If
cmd.Parameters.Add("#UserID", SqlDbType.Int).Value = CInt(Utils.GetLoggedInUserID)
cmd.Parameters.Add("#ProjectName", SqlDbType.NVarChar, 200).Value = ProjectName.ToString
cn.Open()
cmd.ExecuteNonQuery()
End Using
End Sub
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
I wrote the following function to verify log in data for user, but so far its not working as it should and I am sure there is something wrong with it:
Private Sub button2_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles button2.Click
If loginpasswordtx.Text.Length > 1 And loginpasswordtx.Text.Length > 1 And My.Settings.SQLConnectionString.Length > 5 Then
Try
Dim cnn As New SqlConnection(My.Settings.SQLConnectionString)
Dim cmd = New SqlCommand("SELECT AppUser,AppUserPass FROM OrderAppUsers WHERE AppUser=#AppUser AND AppUserPass=#AppUserPass", cnn)
cmd.Parameters.Add(New SqlParameter("#AppUser", createuserAppUser.Text))
cmd.Parameters.Add(New SqlParameter("#AppUserPass", MD5StringHash(loginpasswordtx.Text)))
cnn.Open()
Dim obj As Object = cmd.ExecuteScalar()
If obj = Nothing Then
MsgBox("Faild to Log in, check your log in info")
cnn.Close()
Return
End If
cnn.Close()
Catch ex As SqlException
MsgBox(ex.Message)
Return
End Try
MsgBox("Logged in Successfully")
End If
End Sub
All I get is a null obj even though user and pass exist in the table.
the following code is for adding new users
Try
Dim cnnstring As String = String.Format("Server={0};Database={1};Trusted_Connection=True;", createuserServerTx.Text, createuserDatabaseTx.Text)
Dim cnn As New SqlConnection(cnnstring)
Dim cmd As New SqlCommand("INSERT INTO OrderAppUsers VALUES (#AppUser, #AppUserPass)", cnn)
cmd.Parameters.Add(New SqlParameter("#AppUser", createuserAppUser.Text))
cmd.Parameters.Add(New SqlParameter("#AppUserPass", MD5StringHash(createuserpassword.Text)))
cnn.Open()
cmd.ExecuteNonQuery()
cnn.Close()
MsgBox("User Crated Successfully")
LayoutControl1.Visibility = Windows.Visibility.Collapsed
My.Settings.SQLConnectionString = cnnstring
My.Settings.Save()
Catch ex As SqlException
MsgBox(ex.Message)
End Try
and the function to generate a custom hash
Private Function MD5StringHash(ByVal strString As String) As String
Dim MD5 As New MD5CryptoServiceProvider
Dim Data As Byte()
Dim Result As Byte()
Dim R As String = ""
Dim Temp As String = ""
Data = Encoding.ASCII.GetBytes(strString)
Result = MD5.ComputeHash(Data)
For i As Integer = 0 To Result.Length - 1
Temp = Hex(3 * Result(i) + 1)
If Len(Temp) = 1 Then Temp = "0" & Temp
R += Temp
Next
Return R
End Function
Try the following when adding parameter
cmd.Parameters.AddWithValue("#AppUser", createuserAppUser.Text)
cmd.Parameters.AddWithValue("#AppUserPass", MD5StringHash(loginpasswordtx.Text))
or just stick with what you did but a little different than yours,
cmd.Parameters.Add("#AppUser", SqlDbType.VarChar)
cmd.Parameters("#AppUser").Value = createuserAppUser.Text
cmd.Parameters.Add("#AppUserPass", SqlDbType.VarChar)
cmd.Parameters("#AppUserPass").Value = MD5StringHash(loginpasswordtx.Text)
by the way, when using ExecuteScalar() it only returns single value. So your query can be written as
SELECT COUNT(*)
FROM OrderAppUsers
WHERE AppUser=#AppUser AND AppUserPass=#AppUserPass
and you can use int variable to store its value
Dim obj As int = Cint(cmd.ExecuteScalar())
so the possible values are 0 or the total number of records return.
If obj = 0 Then
MsgBox("Faild to Log in, check your log in info")
'' other codes
End If
and by refractoring your code, use Using -Statement
Using cnn As New SqlConnection(My.Settings.SQLConnectionString)
Using cmd = New SqlCommand("SELECT COUNT(*) FROM OrderAppUsers WHERE AppUser=#AppUser AND AppUserPass=#AppUserPass", cnn)
cmd.Parameters.AddWithValue("#AppUser", createuserAppUser.Text)
cmd.Parameters.AddWithValue("#AppUserPass", MD5StringHash(loginpasswordtx.Text))
cmd.CommandType = CommandType.Text
Try
cnn.Open()
Dim obj As int = Cint(cmd.ExecuteScalar())
If obj = 0 Then
MsgBox("Faild to Log in, check your log in info")
Else
MsgBox("Logged in Successfully")
End If
Catch(ex As SqlException)
MsgBox(ex.Message.ToString())
End Try
End Using
End Using
I checked your code in my local system and it is working fine i mean i was able to validate its return true i analysis and found its return false only when i am adding one space on password text before encrypt can u check in database value is space adding into password value or can u post your encrypt code