I am trying to insert data to a db table using SQL statement with VB.NET.
This is my code:
Registration.aspx:
Imports dbConnect
Imports System.Data.SqlClient
Partial Class Registration
Inherits System.Web.UI.Page
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
End Sub
Protected Sub btnRegister_Click(sender As Object, e As EventArgs) Handles btnRegister.Click
register()
End Sub
Public Sub register()
Dim Username As String = txtUsername.ToString
Dim Surname As String = txtSurname.ToString
Dim Password As String = txtPassword.ToString
Dim Name As String = txtName.ToString
Dim Address1 As String = txtAddress1.ToString
Dim Address2 As String = txtAddress2.ToString
Dim City As String = txtCity.ToString
Dim Email As String = txtEmail.ToString
Dim Country As String = drpCountry.ToString
Dim DOB As Date = calDOB.SelectedDate
Dim Occupation As String = txtOccupation.ToString
Dim WorkLocation As String = txtWorkLocation.ToString
Dim Age As Integer = "20"
Dim ProjectManager As String = "test"
Dim TeamLeader As String = "test"
Dim TeamLeaderID As Integer = 1
Dim ProjectManagerID As Integer = 1
Dim RegistrationDate As Date = Today
Dim ContractType As String = "test"
Dim ContractDuration As Integer = 6
Dim Department As String = "test"
Dim conn As New SqlConnection("Data Source=BRIAN-PC\SQLEXPRESS;Initial Catalog=master_db;Integrated Security=True")
Dim registerSQL As SqlCommand
Dim sqlComm As String
sqlComm = "INSERT INTO users(Username, Password, Name, Surname, Address1, Address2, City, Country, date_of_birth, age, Occupation, department, work_location, project_manager,team_leader, team_leader_id, project_manager_id, date_registration, contract_type, contract_duration) VALUES('" + Username + "','" + Password + "','" + Name + "','" + Surname + "','" + Address1 + "','" + Address2 + "','" + City + "','" + Country + "','" + DOB + "','" + Age + "','" + Occupation + "','" + Department + "','" + WorkLocation + "','" + ProjectManager + "','" + TeamLeader + "','" + TeamLeaderID + "','" + ProjectManager + "','" + RegistrationDate + "','" + ContractType + "','" + ContractDuration + "')"
conn.Open()
registerSQL = New SqlCommand(sqlComm, conn)
registerSQL.ExecuteNonQuery()
conn.Close()
End Sub
End Class
This is my database 'users' table:
I am getting this error message:
Error 1 Operator '+' is not defined for types 'Double' and 'Date'. C:\Users\Brian\Documents\Visual Studio 2012\WebSites\WebSite1\Registration.aspx.vb 51 19 WebSite1(1)
Can anyone tell me whats going on ?
As Lloyd pointed out, parameterize your queries. E.g. (shortened for readability)
sqlComm = "INSERT INTO users(Username, Password, Name) VALUES(#Username, #Password, #Name)"
registerSQL = New SqlCommand(sqlComm, conn)
registerSQL.Parameters.AddWithValue("#Username", Username)
registerSQL.Parameters.AddWithValue("#Password", Password)
registerSQL.Parameters.AddWithValue("#Name", Name)
But to answer your question, use & instead of + to concatenate a String.
Just to give you a starting point
sqlComm = "INSERT INTO users(Username, Password, Name, Surname, Address1, Address2, " +
"City, Country, date_of_birth, age, Occupation, department, work_location, " +
"project_manager,team_leader, team_leader_id, project_manager_id, " +
"date_registration, contract_type, contract_duration) " +
"VALUES(#p1, #p2,#p3,#p4,#p5,#p6,#p7,#p8,#p9,#p10,#p11,#p12,#p13,#p14,#p15," +
"#p16,#p17,#p18,#p19,#p20)"
conn.Open()
registerSQL = New SqlCommand(sqlComm, conn)
registerSQL.Parameters.AddWithValue("#p1", Username)
.....
registerSQL.ExecuteNonQuery()
And when the value to pass to the AddWithValue method is not a string, try to convert to the correct datatype expected by the database field.
registerSQL.Parameters.AddWithValue("#p9", Convert.ToDateTime(DOB))
In this way you don't have to worry about parsing strings with double quotes or automatic conversion of strings to date, moreover, you don't have problems with Sql Injection attacks
Related
my ideas: i select id(max) in table users to write table Userlogin. I get error:
'Conversion failed when converting the varchar value to data type int.'
SELECT idUser
FROM Users
WHERE idUser = (SELECT MAX(idUser) FROM Users)
how to fix error? thank you.
img error: Mycode, Myerror
mycode:
`` `using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
namespace Web_tintuc2
{
public partial class DangKi : System.Web.UI.Page
{
private string connectString = #"Data Source=DESKTOP-
RT3QMVS; Initial Catalog =web_tintuc; Integrated Security=True;";
SqlConnection sql_connect;
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btn_thoat_Click(object sender, EventArgs
e)
{
Response.Redirect("Trangchu.aspx");
//Response.Write("<script>alert('Hello');</script>");
}
protected void btn_dangki_Click(object sender, EventArgs
e)
{
sql_connect = new SqlConnection(connectString);
sql_connect.Open();
string username = txt_username.Text;
string phone = txt_Phone.Text;
string password = txt_password.Text;
string name = txt_name.Text;
string ngaysinh = txt_brithday.Text;
string diachi = txt_diachi.Text;
string email = txt_Email.Text;
DateTime aDateTime = DateTime.Now;
string ngaydangki = aDateTime.ToString("yyyy-MM-dd HH:mm:ss"); // fomat kiểu ngày thánh trong sql server
string active = "Actived";
string IdGruop = "2";
string gioitinh1 = "Nam";
String gioitinh2 = "Nữ";
string sql_check = "select Username from Userlogin
where Username='" + username + "' ";
SqlCommand sql1 = new SqlCommand(sql_check,
sql_connect);
SqlDataReader read = sql1.ExecuteReader();
if (read.Read() == true)
Lb_thongbao.Text = "Username đã tồn tại";
read.Close();
if (Radio_nam.Checked == true)
{
string sql_insert_toUser = " insert into Users(HoTen,Diachi,Email,Dienthoai,gioitinh,ngaysinh,idGroup,ngaydangki,active ) values('" + name + "','" + diachi + "','" + diachi + "','" + email + "','" + phone + "','" + gioitinh1 + "','" + ngaysinh + "','" + IdGruop + "','" + ngaydangki + "','" + active + "')";
SqlCommand sqlcommand1 = new
SqlCommand(sql_insert_toUser, sql_connect);
sqlcommand1.ExecuteNonQuery();
string sql_id_users = "Select top 1 idUser from
Users order by idUser desc";
string sql_insert_to_UserLogin = "insert into
Userlogin(Username,Password,idUser) values('" + username + "','" +
password + "','" + sql_id_users + "') ";
SqlCommand sqlCommand2 = new
SqlCommand(sql_insert_to_UserLogin, sql_connect);
sqlCommand2.ExecuteNonQuery();
}
else if (Radio_nu.Checked == true)
{
string sql_insert_toUser = " insert into Users(HoTen,Diachi,Email,Dienthoai,gioitinh,ngaysinh,idGroup,ngaydangki,active )values('" + name + "','" + diachi + "','" + email + "','" + phone + "','" + gioitinh2 + "','" + ngaysinh + "','" + IdGruop + "','" + ngaydangki + "','" + active + "')";
SqlCommand sqlcommand1 = new SqlCommand(sql_insert_toUser, sql_connect);
sqlcommand1.ExecuteNonQuery();
string sql_id_users = " SELECT idUser FROM Users
WHERE idUser = (SELECT MAX(idUser) FROM Users) ";
string sql_insert_to_UserLogin = "insert into
Userlogin(Username,Password,idUser) values('" + username + "','" +
password + "','"+sql_id_users+"') ";
SqlCommand sqlCommand_2 = new
SqlCommand(sql_insert_to_UserLogin, sql_connect);
sqlCommand_2.ExecuteNonQuery();
}
}
}
}'' '
Your error is coming from your insert statement (line 62). You have single quotes around the variable sql_id_users. Remove the single quotes. It's treating the value as varchar since you have it enclosed in single quotes but it expects an integer.
Suggestion: When you post, please post your code as text and not an image.
I have users form in which they can select some values from checkbox list & values selected in that stores in database in li form. Now I want when users wants to update their form they should be able to see the values checked they have selected earlier.
here is my code.
Insert Form
Private Sub PopulateServices()
Using conn As New MySqlConnection()
conn.ConnectionString = ConfigurationManager _
.ConnectionStrings("conio").ConnectionString()
Using cmd As New MySqlCommand()
cmd.CommandText = "select * from services"
cmd.Connection = conn
conn.Open()
Using sdr As MySqlDataReader = cmd.ExecuteReader()
While sdr.Read()
Dim item As New ListItem()
item.Text = sdr("serviceName").ToString()
item.Value = sdr("serviceName").ToString()
'item.Selected = Convert.ToBoolean(sdr("IsSelected"))
servicesList.Items.Add(item)
End While
End Using
conn.Close()
End Using
End Using
End Sub
Dim selectedServices As String = String.Empty
For Each chk As ListItem In servicesList.Items
If chk.Selected = True Then
selectedServices &= "<li>" + chk.Text + "</li>"
End If
Next
Try
Dim str1 As String = "INSERT INTO hospitals (`hospitalID`,`username`, `password`) values ('" + ID + "', '"selectedServices.ToString + "', '" + mobileNumber + "', '" + membersAutoPassword.Text + "')"
Dim str2 As MySqlDataReader
Dim adapter As New MySqlDataAdapter
Dim command As New MySqlCommand
command.CommandText = str1
command.Connection = con
adapter.SelectCommand = command
con.Open()
str2 = command.ExecuteReader
con.Close()
Response.Redirect("business-added.aspx")
Catch ex As Exception
Response.Write(ex)
End Try
On User Profile page after login they should be able to see what options they have selected. Hence there is a option for users to update their details again
UPDATED
User Profile Page
Private Sub list_business_hospital_Load(sender As Object, e As EventArgs) Handles Me.Load
If Not IsPostBack Then
Try
Dim str As String = "SELECT * FROM hospitals WHERE username='" + Server.HtmlEncode(Request.Cookies("chkusername").Value) + "';"
con.Open()
Dim cmd As New MySqlCommand(str, con)
Dim da As New MySqlDataAdapter(cmd)
Dim dt As New DataTable
Dim lblservice As New Label
For Each chk As ListItem In servicesList.Items
If chk.Selected = True Then
lblservice.Text = String.Concat(lblservice.Text + ",", chk.Value)
End If
Next
da.Fill(dt)
con.Close()
TextId.Text = dt.Rows(0)("hospitalID").ToString
Catch ex As Exception
Response.Write(ex)
End Try
Private Sub PopulateServices()
Using conn As New MySqlConnection()
conn.ConnectionString = ConfigurationManager _
.ConnectionStrings("conio").ConnectionString()
Using cmd As New MySqlCommand()
cmd.CommandText = "select * from services"
cmd.Connection = conn
conn.Open()
Using sdr As MySqlDataReader = cmd.ExecuteReader()
While sdr.Read()
Dim item As New ListItem()
item.Text = sdr("serviceName").ToString()
item.Value = sdr("serviceName").ToString()
'item.Selected = Convert.ToBoolean(sdr("IsSelected"))
servicesList.Items.Add(item)
End While
End Using
conn.Close()
End Using
End Using
End Sub
Private Sub updateInfo_Click(sender As Object, e As EventArgs) Handles updateInfo.Click
Try
Dim con As New MySqlConnection
Dim query As New MySqlCommand
con.ConnectionString = ConfigurationManager _
.ConnectionStrings("conio").ConnectionString()
query.Connection = con
con.Open()
Dim selectedServices As String = String.Empty
For Each chk As ListItem In servicesList.Items
If selectedServices.Contains("<li>" & chk.Text & "</li>") Then
'display item as selected
chk.Selected = True
End If
Next
query.CommandText = "UPDATE hospitals SET name = '" + businessName.Text + "', contactPerson = '" + contactPerson.Text + "', websiteName = '" + websiteName.Text + "', email = '" + emailName.Text + "', phone1 = '" + phone1.Text + "', phone2 = '" + phone2.Text + "', mobileNumber = '" + mobile.Text + "', buildingName = '" + buildingName.Text + "', streetName = '" + address.Text + "', landmark = '" + landmark.Text + "', areaName = '" + areaName.Text + "', city = '" + suburb.Text + "', state = '" + state.Text + "', zipCode = '" + zip.Text + "', overview = '" + overview.Text + "', registration = '" + regNo.Text + "', establishment = '" + foundation.Text + "', founder = '" + founderName.Text + "', generalBed = '" + GeneralBeds.Text + "', icuBed = '" + ICU.Text + "', consultancyFees = '" + consultinfees.Text + "', mondayFrom = '" + mondayFrom.Text + "', mondayTo = '" + mondayTo.Text + "', tuesdayFrom = '" + tuesdayFrom.Text + "', tuesdayTo = '" + tuesdayTo.Text + "', wednesdayFrom = '" + wedFrom.Text + "', wednesdayTo = '" + wedTo.Text + "', thursdayFrom = '" + thursdayFrom.Text + "', thursdayTo = '" + thursdayTo.Text + "', fridayFrom = '" + fridayFrom.Text + "', fridayTo = '" + fridayTo.Text + "', saturdayFrom = '" + saturdayFrom.Text + "', saturdayTo = '" + saturdayTo.Text + "', sundayFrom = '" + sundayFrom.Text + "', sundayTo = '" + sundayTo.Text + "', visitFrom = '" + visitFrom.Text + "', visitTo = '" + visitTo.Text + "', bestKnownFor = '" + bestknowFor.Text + "' WHERE hospitalID = '" + TextId.Text + "'"
query.ExecuteNonQuery()
con.Close()
Response.Write("<script language='javascript'>alert('Information updated successfully.');</script>")
Catch ex As Exception
Response.Write(ex)
End Try
End Sub
Please check below,
'Here I assume that, you will call PopulateServices to populate servicesList checkbox list
PopulateServices()
'You didn't mention fieldName, so I assume that field in database is :
'savedServices - This will be li tags like, <li>item 1</li><li>item 2</li>
'Now loop through all items within checkbox list
For Each chk As ListItem In servicesList.Items
'You need to check whether this item saved in database or not?
'If item already saved in database, display as selected
If savedServices.Contains("<li>" & chk.Text & "</li>") Then
'display item as selected
chk.selected = true
End If
Next
It suppose there is chart to be appeared. But, it doesnt as there is problem regarding dbnull issue. This happen when either one of three select statement has no data.
Dim user As String = Session("NoMatrik")
Dim resultId As Object = Session("max")
Dim idQuery = "select max(resultid) as id from tblResult where result_nomatric = #matric and result_quiz_id = 1 UNION All " +
"select max(resultid) as id from tblResult where result_nomatric = #matric and result_quiz_id = 2 UNION All " +
"select max(resultid) as id from tblResult where result_nomatric = #matric and result_quiz_id = 3"
conn.Open()
Dim cmdGetId As New SqlCommand(idQuery, conn)
cmdGetId.Parameters.AddWithValue("#matric", user)
Dim maxIDs As SqlDataReader = cmdGetId.ExecuteReader
Dim IDs As String = ""
While maxIDs.Read
IDs += maxIDs("id").ToString() + ", "
End While
maxIDs.Close()
IDs = IDs.Substring(0, IDs.Length - 2)
Dim cmdString = "Select tblResult.result_quiz_id as Quiz,count(TblAnswer.AnswerType) as answerCount , TblAnswer.AnswerType " +
"from TblResultDetail inner join TblAnswer on TblResultDetail.ResultDetail_Answer_Id = TblAnswer.AnswerId " +
"inner join tblResult on tblResult.resultid = TblResultDetail.ResultDetail_Result_Id " +
"where TblResultDetail.ResultDetail_Result_Id in (" + IDs + ") " +
"group by TblAnswer.AnswerType, tblResult.result_quiz_id order by TblAnswer.AnswerType"
Dim cmd As New SqlCommand(cmdString, conn)
If IsDBNull(resultId) Then
Label1.Visible = True
chrtResult.Visible = False
Else
Dim dr1 As SqlDataReader
dr1 = cmd.ExecuteReader
While dr1.Read()
Dim tempArr(0) As Double
Dim count As Double = dr1("answerCount")
tempArr(0) = count
Dim Type As String = dr1("AnswerType").ToString()
Dim level As Integer = dr1("Quiz")
chrtResult.Series(Type).Points(level - 1).YValues = tempArr
End While
End If
conn.Close()
End If
End Sub
an error, Incorrect syntax near '(' appear at line dr1 = cmd.ExecuteReader. So , how I want to fix this error?
Update your first query to exclude any Null values using a HAVING clause like so:
Dim idQuery = "select max(resultid) as id from tblResult " +
"where result_nomatric = #matric and result_quiz_id = 1 " +
"having max(resultid) is not null " +
"UNION All " +
"select max(resultid) as id from tblResult " +
"where result_nomatric = #matric and result_quiz_id = 2 " +
"having max(resultid) is not null " +
"UNION All " +
"select max(resultid) as id from tblResult " +
"where result_nomatric = #matric and result_quiz_id = 3 " +
"having max(resultid) is not null"
The having max(resultid) is not null will exclude any nulls in your UNION ALL.
If there are no IDs returned, you simply need to do a check on this before you execute your next block of code and do as #DmitriE suggests with the adding of quotes. Reorganise it to look like:
While maxIDs.Read
IDs += "'" + maxIDs("id").ToString() + "', "
End While
If IDs = "" Then
Label1.Visible = True
chrtResult.Visible = False
Else
IDs = IDs.Substring(0, IDs.Length - 2)
Dim cmdString = "Select ....."
Dim dr1 As SqlDataReader
dr1 = cmd.ExecuteReader
While dr1.Read()
' YOUR WHILE LOOP CODE HERE'
End While
End If
This should be
While maxIDs.Read
IDs += "'" + maxIDs("id").ToString() + "', "
End While
and then you need to remove last single quote.
in clause should follow this format: where x.id in ('id1', 'id2', 'idN')
I have been hearing about parametrized queries every time I ask a question about database here. It looks like I am not using parametrized queries and my code may suffer from SQL injection. So here is my code:
public void CreateStudent(int ID, String status, String email, String firstName, String lastName, String password, String level, String program)
{
SqlConnection con = new SqlConnection(GetConnectionString());
string query1 = "insert into StudentTable(Name,Surname,ID,email,level,program,status,password,Type) values ("
+ "'" + firstName + "'" + "," + "'" + lastName + "'" + ","
+ "'" + ID + "'" + "," + "'" + email + "'" + "," + "'" + level + "'" + "," + "'" + program + "'" + "," + "'" + status + "'"
+ "," + "'" + password + "'" + "," + "'" + "Student" + "'" + ")";
SqlCommand command = new SqlCommand(query1,con);
int result;
con.Open();
result = command.ExecuteNonQuery();
con.Close();
}
Here is what I have tried:
SqlConnection con = new SqlConnection(GetConnectionString());
string query1 = "insert into StudentTable(Name,Surname,ID,email,level,program,status,password,Type) values(#firstName,#lastName,#ID,#email,#level,#program,#status,#password,Student)";
SqlCommand command = new SqlCommand(query1,con);
command.Parameters.AddWithValue("#firstName", firstName);
command.Parameters.AddWithValue("#lastName", lastName);
command.Parameters.AddWithValue("#ID", ID);
command.Parameters.AddWithValue("#email", email);
command.Parameters.AddWithValue("#level", level);
command.Parameters.AddWithValue("#program", program);
command.Parameters.AddWithValue("#status", status);
command.Parameters.AddWithValue("#password", password);
int result;
con.Open();
result = command.ExecuteNonQuery();
con.Close();
This gives an error saying that Student is an invalid column name. Actually, here I try to use "Student" as a string value to be added to the column Type. Can somebody write this query as a parametrized query so that I can understand it?
In that case it should be 'Student'
SqlConnection con = new SqlConnection(GetConnectionString());
string query1 = "insert into StudentTable(Name,Surname,ID,email,level,program,status,password,Type) values(#firstName,#lastName,#ID,#email,#level,#program,#status,#password,'Student')";
SqlCommand command = new SqlCommand(query1,con);
command.Parameters.AddWithValue("#firstName", firstName);
command.Parameters.AddWithValue("#lastName", lastName);
command.Parameters.AddWithValue("#ID", ID);
command.Parameters.AddWithValue("#email", email);
command.Parameters.AddWithValue("#level", level);
command.Parameters.AddWithValue("#program", program);
command.Parameters.AddWithValue("#status", status);
command.Parameters.AddWithValue("#password", password);
int result;
con.Open();
result = command.ExecuteNonQuery();
con.Close();
Check this link
public void CreateStudent(int ID, String status, String email, String firstName, String lastName, String password, String level, String program)
{
SqlConnection con = new SqlConnection(GetConnectionString());
using (
SqlCommand command =
new SqlCommand(
#"insert into StudentTable(Name,Surname,ID,email,level,program,status,password,Type) values
(#name, #surname, #id, #email, #level, #program, #status,#password,'Student')",
con))
{
//
// Add new SqlParameter to the command.
//
command.Parameters.Add(new SqlParameter("name", firstName));
command.Parameters.Add(new SqlParameter("surname", lastName));
command.Parameters.Add(new SqlParameter("id", ID));
command.Parameters.Add(new SqlParameter("email", email));
command.Parameters.Add(new SqlParameter("level", level));
command.Parameters.Add(new SqlParameter("program", program));
command.Parameters.Add(new SqlParameter("status", status));
int result;
con.Open();
result = command.ExecuteNonQuery();
con.Close();
}
}
i created a simple advanced search page for web application, i thought sharing it with you might help beginners
the following is an example of an advanced search page for an employee database using VB.Net
the following is the code behind page
Imports System.Data.OleDb
Partial Class searchme
Inherits System.Web.UI.Page
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim mydb As New OleDbConnection
mydb = New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source= |datadirectory|employee.mdb;Persist Security Info=True")
mydb.Open()
Dim sqlstring = "select * from [dataview] where "
If MRNTextBox1.Text <> "" Then sqlstring = sqlstring + "[code] like '%" + CodeNameTextBox1.Text + "%' OR [EmployeeName] like '%" + CodeNameTextBox1.Text + "%' AND "
If GOVDDL.SelectedItem.Text <> "--Please Select--" Then sqlstring = sqlstring + "[Governorate] ='" + GOVDDL.SelectedItem.Text + "' AND "
If genderddl.SelectedItem.Text <> "--Please Select--" Then sqlstring = sqlstring + "[Gender] ='" + genderddl.SelectedItem.Text + "' AND "
If DateEmploymentFrom.Text <> "" And DateEmploymentTo.Text <> "" Then sqlstring = sqlstring + "[DateEmployment] >= #" + DatumKonvert1.DK1(DateEmploymentFrom.Text) + "# AND [Datepresentation] <= #" + DatumKonvert1.DK1(DateEmploymentTo.Text) + "# AND "
If DepartmentDDL.SelectedItem.Text <> "--Please Select--" Then sqlstring = sqlstring + "[Department] ='" + DepartmentDDL.SelectedItem.Text + "' AND "
sqlstring = Left(sqlstring, Len(sqlstring) - 5) + " order by " + OrderByDDL.SelectedItem.Text
Dim myds As New AccessDataSource
myds.DataFile = "~\App_Data\employee.mdb"
myds.SelectCommand = sqlstring
' Dim Mygrid As New GridView
Mygrid.DataSource = myds
Mygrid.DataBind()
' Me.form1.Controls.Add(Mygrid)
mydb.Close()
RecCount.Text = "Filtered Record Count = " + mygrid.Rows.Count.ToString
Session("dsource") = myds
Response.Redirect("sresults.aspx")
End Sub
End Class
you did a good job, also try the following
link text
link text