Copying data from one table to another (along with some other data) - asp.net

Is possible to transfer data from one table into an empty table along with a other data? Is it possible to do that with a single SQL statement? What I've tried so far produces no errors but the data from the original table is not transferred to the empty table.
I've include my code below and I'd appreciate any advice. I suspect there's a problem with the database connection, but I am still new to programming and I can't see the problem.
Imports System.Data.SqlClient
Public Class uploadSuccess
Inherits System.Web.UI.Page
Dim con As SqlConnection
Dim cmd As SqlCommand
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
End Sub
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
con = New SqlConnection("Data Source=127.0.0.1; User Id=user;Password=pass;Initial Catalog=catalog;")
con.Open()
cmd = con.CreateCommand()
cmd.Connection = con
Dim intCount As Int32
Dim getReceipt As Int32
Dim femtocellrow As Int32
Dim noreceipt As Int32
Dim username As String
Dim client As String
Dim comName As String
noreceipt = Session("recNo")
username = Session("username")
comName = Session("compName")
'Response.Write("noreceipt" & noreceipt)
cmd.CommandText = "SELECT COUNT(*) AS RETURNCOUNT FROM dbo.tempTable"
intCount = cmd.ExecuteScalar
' Response.Write("count " & intCount)
cmd.CommandText = "SELECT noDevices FROM dbo.Receipt WHERE receiptNo= #noreceipt"
cmd.Parameters.AddWithValue("#noreceipt", noreceipt)
getReceipt = cmd.ExecuteScalar
'Response.Write("receipt " & getReceipt)
cmd.CommandText = "SELECT COUNT(*) AS RETURNCOUNT FROM dbo.femtocell WHERE receiptNo= #norec"
cmd.Parameters.AddWithValue("#norec", noreceipt)
femtocellrow = cmd.ExecuteScalar
'Response.Write("femrow " & femtocellrow)
cmd.CommandText = "SELECT clientID FROM dbo.Receipt WHERE companyName=#comName"
cmd.Parameters.AddWithValue("#comName", comName)
client = cmd.ExecuteScalar
'Response.Write("client " & client)
con.Close()
Dim rowsAffected As Integer = 0
Dim myConnectionString As String = "Data Source=192.168.18.30; User Id=sa;Password=google;Initial Catalog=femtocell;"
Dim myConnection As New SqlConnection(myConnectionString)
If (femtocellrow < getReceipt) & (intCount < femtocellrow) Then
'Dim myQuery As String = "SELECT ([uploadID],[clientID],[receiptNo],[compName],[state],[town],[district],[siteAddress],[latitude],[longitude],[type],[serialNo],[man],[model],[pwr],[appNo],[manAntenna],[modelAntenna],[height],[gain],[emission],[bhaul],[strucType],[covType],[cov],[spectBand],[txFreq],[rxFreq],[bw],[regFee],[uspArea],[commDate],[compName]) INTO dbo.femtocell (username,client,noreceipt,comName,[State],[Town],[District],[Site_Address],[Latitude],[Longitude],[Equipment_Type],[Equipment_Serial_No],[Equipment_Man],[Equipment_Model],[Equipment_Pwr_Mw],[Equipment_App_No],[Antenna_Man],[Antenna_Model],[Antenna_Height_m],[Antenna_Gain_Db],[antenna_emission],[Bhaul],[Struc_Type],[Cov_Type],[Cov_m],[Spect_Band],[Tx_Freq_MHz],[Rx_Freq_MHz],[Bw_KHz],[Reg_Fee_RM],[USP_area],[Comm_Date]) FROM dbo.tempTable"
' Dim myQuery As String = "INSERT INTO dbo.femtocell ([uploadID],[clientID],[receiptNo],[compName],[state],[town],[district],[siteAddress],[latitude],[longitude],[type],[serialNo],[man],[model],[pwr],[appNo],[manAntenna],[modelAntenna],[height],[gain],[emission],[bhaul],[strucType],[covType],[cov],[spectBand],[txFreq],[rxFreq],[bw],[regFee],[uspArea],[commDate],[compName]) VALUES (SELECT 'username','client','noreceipt','comName',[State],[Town],[District],[Site_Address],[Latitude],[Longitude],[Equipment_Type],[Equipment_Serial_No],[Equipment_Man],[Equipment_Model],[Equipment_Pwr_Mw],[Equipment_App_No],[Antenna_Man],[Antenna_Model],[Antenna_Height_m],[Antenna_Gain_Db],[antenna_emission],[Bhaul],[Struc_Type],[Cov_Type],[Cov_m],[Spect_Band],[Tx_Freq_MHz],[Rx_Freq_MHz],[Bw_KHz],[Reg_Fee_RM],[USP_area],[Comm_Date]FROM dbo.tempTable"
Dim myQuery As String = "INSERT INTO dbo.femtocell ([state],[town],[district],[siteAddress],[latitude],[longitude],[type],[serialNo],[man],[model],[pwr],[appNo],[manAntenna],[modelAntenna],[height],[gain],[emission],[bhaul],[strucType],[covType],[cov],[spectBand],[txFreq],[rxFreq],[bw],[regFee],[uspArea],[commDate]) SELECT [State],[Town],[District],[Site_Address],[Latitude],[Longitude],[Equipment_Type],[Equipment_Serial_No],[Equipment_Man],[Equipment_Model],[Equipment_Pwr_Mw],[Equipment_App_No],[Antenna_Man],[Antenna_Model],[Antenna_Height_m],[Antenna_Gain_Db],[antenna_emission],[Bhaul],[Struc_Type],[Cov_Type],[Cov_m],[Spect_Band],[Tx_Freq_MHz],[Rx_Freq_MHz],[Bw_KHz],[Reg_Fee_RM],[USP_area],[Comm_Date]FROM dbo.tempTable"
Dim myCommand As New SqlCommand(myQuery, myConnection)
Try
myConnection.Open()
rowsAffected = myCommand.ExecuteNonQuery()
Catch ex As Exception
Response.Write(ex.Message)
Finally
myConnection.Close()
End Try
Else
Dim message As String = "Number of devices submitted is invalid."
Dim sb As New System.Text.StringBuilder()
sb.Append("alert('")
sb.Append(message)
sb.Append("');")
ClientScript.RegisterOnSubmitStatement(Me.GetType(), "alert", sb.ToString())
End If
End Sub
End Class

Maybe one of these will help:
SQL SERVER – Insert Data From One Table to Another Table – INSERT INTO SELECT – SELECT INTO TABLE
sqlauthority.com
copy all rows of a table to another table
stackoverflow.com
C# – Bulk copying data into MS SQL Server with DataTables
myadventuresincoding.wordpress.com

Related

Asp.net multible table access vb.net

and good day..
I have a code of asp.net in vb.net and work fine for one table but i need to add multible table of( master and dr ) to code the data is the sum from the two table but its different. can anyone help me..thanks advance for all
Private Sub getData(ByVal user As String)
Dim dt As New DataTable()
Dim connectionString As String
Dim connection As OleDbConnection
connectionString = ConfigurationManager.ConnectionStrings("Data_For_netConnectionString").ToString
connection = New OleDbConnection(connectionString)
connection.Open()
Dim sqlCmd As New OleDbCommand("SELECT * from master WHERE UserID = #user", connection)
sqlCmd.CommandText = _
"SELECT name, manistry, university, send, card FROM master "
Dim sqlDa As New OleDbDataAdapter(sqlCmd)
sqlCmd.Parameters.AddWithValue("#user", user)
sqlDa.Fill(dt)
If dt.Rows.Count > 0 Then
TextBox1.Text = dt.Rows(0)("manistry").ToString
TextBox2.Text = dt.Rows(0)("university").ToString
TextBox4.Text = dt.Rows(0)("send").ToString
TextBox21.Text = dt.Rows(0)("card").ToString
name.Text = dt.Rows(0)("name").ToString
End If
connection.Close()
End Sub

VB ASP Array prevent multi reading

This is my 'code':
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button1.Click
Dim arrName As New ArrayList()
Dim con As New SqlConnection
Dim cmd As New SqlCommand
Dim rdr As SqlDataReader
con.ConnectionString = "Data Source=.\sqlexpress;Initial Catalog=GradingSystemSample;Integrated Security=True;Pooling=False"
cmd.Connection = con
con.Open()
cmd.CommandText = "select numb FROM Table2 "
rdr = cmd.ExecuteReader
If rdr.HasRows Then
While rdr.Read
arrName.Add(rdr("numb"))
For Each pno As String In arrName
MsgBox(pno)
Next
End While
End If
End sub
I want my output to be:
639057318820
639355514108
639056784959
but my code output is:
639057318820
639057318820
639355514108
639057318820
639355514108
639056784959
it seems like my code is reading is reading from the indexes 0 before reading the next index. help me guys?
Change
If rdr.HasRows Then
While rdr.Read
arrName.Add(rdr("numb"))
For Each pno As String In arrName
MsgBox(pno)
Next
End While
End If
to
If rdr.HasRows Then
While rdr.Read
arrName.Add(rdr("numb"))
End While
End If
For Each pno As String In arrName
MsgBox(pno)
Next

Getting error for Data Reader in vb.net

Im facing the error when execute the data reader command in vb.net. it throw handling. This field like when you enter employee id in textbox then it will capture in database for other field name,department.
here is my code
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
Dim conn As New MySql.Data.MySqlClient.MySqlConnection
Dim strConnectionString As String =ConfigurationManager.ConnectionStrings("testConnectionString").ConnectionString
Dim sqlQuery As String = "SELECT * hr_record WHERE Emplid='" & txt1.Text & "'"
Using sqlConn As New MySqlConnection(strConnectionString)
Using sqlComm As New MySqlCommand()
With sqlComm
.CommandText = sqlQuery
End With
Try
sqlConn.Open()
Dim sqlReader As MySqlDataReader = sqlComm.ExecuteReader()
While sqlReader.Read()
txt1.Text = sqlReader("Emplid").ToString()
TextBox1.Text = sqlReader("Nama").ToString()
TextBox2.Text = sqlReader("DeptDesc").ToString()
End While
Catch ex As MySqlException
MessageBox.Show(ex.Message)
End Try
End Using
End Using
End Sub
Try to change your select query like
Dim sqlQuery As String = "SELECT * from hr_record WHERE Emplid='" & txt1.Text & "'"
Note:- Cannot use code like that in Page_Load.Try to make one Function and call that function from Page_Load and always use Parameterized query.
Updated answer:
Page_Load
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
DataBind()
End Sub
Outside Method:
Public Sub DataBind()
Dim sConnection As String = "server=(local);uid=sa;pwd=PassWord;database=DatabaseName"
Using Con As New MySqlConnection(sConnection)
Con.Open()
Using Com As New MySqlCommand("SELECT * from hr_record WHERE Emplid='"txt1.Text
"'", Con)
Using RDR = Com.ExecuteReader()
If RDR.HasRows Then
Do While RDR.Read
txt1.Text = RDR.Item("Emplid").ToString()
TextBox1.Text = RDR.Item("Nama").ToString()
TextBox2.Text = RDR.Item("DeptDesc").ToString()
Loop
End If
End Using
End Using
Con.Close()
End Using
End Sub
Note:Try to implement your logic like that and also modified as per your requirements.
Hope it works.
You try to get Emplid in page load,but it's still nothing you should use button to check if Emplid exist
Thanks to all thanks helping me..finally this code it works thanks to all .
this the code will be function
Dim conn As New MySql.Data.MySqlClient.MySqlConnection
Dim strConnectionString As String = ConfigurationManager.ConnectionStrings("testConnectionString").ConnectionString
Using sqlConn As New MySqlConnection(strConnectionString)
sqlConn.Open()
Using sqlComm As New MySqlCommand()
sqlComm.Connection = sqlConn
With sqlComm
.CommandText = "SELECT * from hr_record WHERE Emplid='" & txt1.Text & "'"
End With
Try
Dim sqlReader As MySqlDataReader = sqlComm.ExecuteReader()
While sqlReader.Read()
txt1.Text = sqlReader("Emplid").ToString()
TextBox1.Text = sqlReader("Nama").ToString()
txtdep.Text = sqlReader("DeptDesc").ToString()
End While
Catch ex As MySqlException
MessageBox.Show(ex.Message)
End Try
sqlConn.Close()
End Using
End Using
End Sub

Creating Control Arrays in Vb 2010 with table column names not reading Rows

I am having problems with Creating Control Arrays and getting the Column Names for a table, I know that my string works as I have used the outputted string straight as a SQL query, the problem lies where it seems not to find any of the rows in the table(that i know are their, using the If lrd.HasRows Then I have seen that it does not find any rows (lrd.HasRows = False). Is their a diffent Connection string for INFORMATION_SCHEMA.COLUMNS ?
'Finds the Column Name
Public Sub findSQLColumnName(ByRef i As Integer, ByRef OutputValue As String, ByVal tableName As String)
Dim con As New SqlConnection
Dim cmd As New SqlCommand
Dim lrd As SqlDataReader
Dim TableNameParm As New SqlParameter("Tablename", tableName) 'adds in the new paramenter UserName
TableNameParm.Direction = ParameterDirection.Output
Dim LocationParm As New SqlParameter("Location", i) 'adds in the new paramenter UserName
LocationParm.Direction = ParameterDirection.Input
Call FindConnectionString(con) ' finds connection string
cmd.Parameters.Add(TableNameParm)
cmd.Parameters.Add(LocationParm)
Call SQLSELECT_WHERE("INFORMATION_SCHEMA.COLUMNS", "COLUMN_NAME AS Output, ORDINAL_POSITION", True, " (TABLE_NAME = #Tablename) AND (ORDINAL_POSITION = #Location)", con, cmd, lrd)
Try
' While lrd.Read() ' code writen within here for what is to be done with selected data.
'Call findSQLColumnValue("Output", lrd, OutputValue)
'End While
If lrd.HasRows Then
lrd.Read()
Call findSQLColumnValue("Output", lrd, OutputValue)
lrd.Close()
'Close connection before Redirecting.
Else
lrd.Close()
End If
' Catch ex As Exception
Finally
con.Close()
End Try
End Sub
'Finds the value of a Column
Public Sub findSQLColumnValue(ByRef ColumnName As String, loader As SqlDataReader, ByRef OutputValue As String)
OutputValue = (Convert.ToString(loader(ColumnName))).Trim
End Sub
'Button Click (Creates the control array)
Protected Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim SQLCode As New SQLCode
Dim TableLength As Integer
Dim lblText(100) As String
Call SQLCode.SQLFindNoColumns("PatientClinicalinformation", TableLength, lblTitlePatient, lblText)
For i As Int16 = 1 To TableLength
' Create the label control and set its text attribute
Dim Label2 As New Label
Call SQLCode.findSQLColumnName(i.ToString, lblText(i), "PatientClinicalinformation")
Label2.Text = lblText(i)
Dim Literal2 As New Literal
Literal2.Text = "<br />"
' Add the control to the placeholder
PlaceHolder1.Controls.Add(Label2)
Label2.ID = "lbl" & i
PlaceHolder1.Controls.Add(Literal2)
Next
End Sub
'SelectWhere
Public Sub SQLSELECT_WHERE(ByVal Tables As String, ByVal Columns As String, ByVal WHERE As Boolean, ByVal WHEREStatement As String, ByRef connection As SqlConnection, ByRef command As SqlCommand, ByRef loader As SqlDataReader)
connection.Open()
command.Connection = connection
If WHERE = False Then
command.CommandText = " SELECT " & Columns & " FROM " & Tables
End If
If WHERE = True Then
command.CommandText = " SELECT " & Columns & " FROM " & Tables & " WHERE " & WHEREStatement
End If
command.CommandText = command.CommandText
loader = command.ExecuteReader()
End Sub
I found the solution! the code all worked there was a problem with the array TableNameParm
Dim TableNameParm As New SqlParameter("Tablename", tableName) 'adds in the new paramenter UserName
TableNameParm.Direction = ParameterDirection.Output
Dim LocationParm As New SqlParameter("Location", i) 'adds in the new paramenter UserName
LocationParm.Direction = ParameterDirection.Input
The TableNameParm.Direction should be an input but is set to a Output
Dim TableNameParm As New SqlParameter("Tablename", tableName) 'adds in the new paramenter UserName
TableNameParm.Direction = ParameterDirection.Input
Dim LocationParm As New SqlParameter("Location", i) 'adds in the new paramenter UserName
LocationParm.Direction = ParameterDirection.Input
It's hard to say without knowing the function SQLSELECT_WHERE, but it's possible one or more of the parameters is not correct. Try skipping that function and use
cmd = New SqlCommand("SELECT ... WHERE", conn)
You can also test the number of rows by using count(*) in the query.

what is the problem in this query it will delete all records of table !

Protected Sub GridView3_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles GridView3.RowCommand
For Each myRow As GridViewRow In GridView3.Rows
'Find the checkbox
Dim lab1 As Label = DirectCast(myRow.FindControl("Label1"), Label)
If e.CommandName = "Sumit" Then
Dim cmd As New Data.SqlClient.SqlCommand
Dim con As New Data.SqlClient.SqlConnection(constr)
Try
Dim strSql As String = "DELETE * FROM hotels WHERE hotelid =" & lab1.Text
'------------"
con.Open()
cmd.Connection = con
cmd.CommandText = strSql
cmd.ExecuteNonQuery()
Catch ex As Exception
Response.Write(ex.Message)
Finally
cmd.Dispose()
con.Dispose()
End Try
End If
Next
GridView3.DataBind()
End Sub
I'm not sure why you think that will delete everything in the table, as I'm fairly certain it will not even execute. DELETE does not require any columns or * to be specified. It should just be DELETE FROM hotels WHERE [etc, etc].
Also, you should seriously consider giving this article a read: How To: Protect From SQL Injection in ASP.NET. Especially "Step 3. Use Parameters with Dynamic SQL", which detail how you could change your code to prevent SQL injection.
I believe what you are looking for is this:
Protected Sub GridView3_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles GridView3.RowCommand
Dim myRow As GridViewRow = DirectCast((System.Web.UI.Control)(sender)).NamingContainer, GridViewRow)
'Find the checkbox
Dim lab1 As Label = DirectCast(myRow.FindControl("Label1"), Label)
If e.CommandName = "Sumit" Then
Dim cmd As New Data.SqlClient.SqlCommand
Dim con As New Data.SqlClient.SqlConnection(constr)
Try
Dim strSql As String = "DELETE FROM hotels WHERE hotelid =" & lab1.Text
'------------"
con.Open()
cmd.Connection = con
cmd.CommandText = strSql
cmd.ExecuteNonQuery()
Catch ex As Exception
Response.Write(ex.Message)
Finally
cmd.Dispose()
con.Dispose()
End Try
End If
GridView3.DataBind()
End Sub
The syntax may be off I'm not too familiar with VB. As well it would be better to pass the ID of the hotel record in the e.CommandArgument thus you would not have to retrieve it from a label on the page. It is deleting all your records because you are looping through all your rows in the grid view and deleting each record.

Resources