I have a plain text file that contains one column of numbers, and in a web client take the numbers and transfer them into a SQL Database. After retrieving the file, I store the contents in a temporary DataTable, then using SqlBulkCopy, attempt to transfer the DataTable to the database. However, once I run the web client and import the file, the program hangs. The code is listed below for what I've done so far.
Transferring Files to DataTable
private DataTable readTextFile()
{
DataTable dt = new DataTable();
FileUpload file = new FileUpload();
dt.Columns.Add("Claim Number", typeof(Int32));
file = (FileUpload)grdCriteria.FindControl("exportUpload");
StreamReader read = new StreamReader(file.PostedFile.FileName);
while ((read.ReadLine()) != null)
dt.Rows.Add((Int32.Parse(read.ReadLine())));
return dt;
}
Insert DataTable into SQL Database
DataTable dt = readTextFile();
SqlBulkCopy bk = new SqlBulkCopy(Profile.ConnectionKey.CAM);
bk.DestinationTableName = dt.TableName;
bk.WriteToServer(dt);
Thanks!
Related
I need to load data from Table 1. After loading it to a datagrid view, I have to save it to another table (Table2).
'' Load data
Dim cmdSQL As String = "SELECT * FROM Table1"
Dim ds_Tbl As New DataSet
Dim cmdBuilder As New SqlClient.SqlCommandBuilder
Dim da As New SqlClient.SqlDataAdapter(cmdSQL, connection)
cmdBuilder = New SqlCommandBuilder(da)
da.Fill(ds_Tbl, "Table2")
dgvTables.DataSource = ds_Tbl.Tables(0) '
'' Save data
Me.Validate()
da.Update(ds_Tbl.Tables("Table2"))
ds_Tbl.AcceptChanges()
I prefer to use command builder because this code is placed inside a loop for me to able to load various tables to one datagrid one at a time then save it to other designated table. Loading went okay but saving was unsuccessful. Please help.
I have a desktop application (VB.NET and MS Access) that work so fine and it can only be used on one computer (no shared database). I am looking at the possibility where the application can be used by 5 to 10 people at a time (Client/Server perhaps).
I decided to use MySQL for the database, which is up and running but I am still to figure where best to save images that will be uploaded by different users so that it can be accessible to all users.
Edit:
Should it be stored on shared folder in the server? If this is the best possible way, please how can I achieve this?
Thanks
If you have moved to MySQL (if you only have 5 to 10 users, I would save go to MS sql express, but you might stay with MySQL because of size restrictions) you could store the pictures in the database.
MySQL supports a BLOB data type (which is meant to store binary data).
There are some good examples of how to save and retrieve images over on codeproject http://www.codeproject.com/Articles/437937/Save-and-Retrieve-Image-from-a-SQL-Server-Database Store picture to database; retrieve from db into Picturebox
but the basic idea is something like this (to store the data)
Dim mstream As New System.IO.MemoryStream()
PbPicture.Image.Save(mstream, System.Drawing.Imaging.ImageFormat.Jpeg)
Dim arrImage() As Byte = mstream.GetBuffer()
FileSize = mstream.Length
Dim sqlcmd As New MySqlCommand
Dim sql As String
mstream.Close()
sql = "insert into [your table] (picture, filename, filesize)
VALUES(#File, #FileName, #FileSize)"
Try
conn.Open()
With sqlcmd
.CommandText = sql
.Connection = conn
.Parameters.AddWithValue("#FileName", filename)
.Parameters.AddWithValue("#FileSize", FileSize)
.Parameters.AddWithValue("#File", arrImage)
.ExecuteNonQuery()
End With
Catch ex As Exception
MsgBox(ex.Message)
Finally
conn.Close()
End Try
and something like this (to get the data back from the database - PbPicture is a picturebox in this example)
Dim adapter As New MySqlDataAdapter
adapter.SelectCommand = Cmd
data = New DataTable
adapter = New MySqlDataAdapter("select picture from [yourtable]", conn)
commandbuild = New MySqlCommandBuilder(adapter)
adapter.Fill(data)
Dim lb() As Byte = data.Rows(0).Item("picture")
Dim lstr As New System.IO.MemoryStream(lb)
PbPicture.Image = Image.FromStream(lstr)
PbPicture.SizeMode = PictureBoxSizeMode.StretchImage
lstr.Close()
I'm trying to dynamically get my data source from my database using a query but it shows the wrong report source even though the query and data source is correct.
Public DA As New SqlDataAdapter
Public DS As DataSet
Public Function executeViaSQL(ByVal sqlquery As String) As DataSet
DS = New DataSet
DA = New SqlDataAdapter(sqlquery, Conn)
DA.Fill(DS, 0)
Return DS
End Function
Private Sub formload
Dim RS As New rptDaily
DS = New DataSet
DS = executeViaSQL(query) 'query is public and has a stored query
RS.Load()
RS.SetDataSource(DS.Tables(0))
CrystalReportViewer1.ReportSource = RS
End Sub
The report is showing the default report source even though I've set the report source to a dataset from my database.
Additional information, rptDaily.rpt properties:
Build Action: Embedded Resource
Copy to Output Directory: Do not copy
Custom Tool: CrystalDecisions.VSDesigner.CodeGen.ReportCodeGenerator
Custom Namespace: Blank
I think the problem is the reportsource is pulling data from my database instead of the dataset. But still don't know how to resolve this problem.
I would like to insert a binary value into the database without using FileUpload.
I searched for tutorials, samples and i saw only codes like:
Dim fs As Stream = FileUpload1.PostedFile.InputStream
Dim br As New BinaryReader(fs)
Dim bytes As Byte() = br.ReadBytes(fs.Length)
But, I have already a file/data in my asp:Image> with the use of a Canvas,
var dataURL = canvas.toDataURL();
which is data:image/png;base64,iVBORw0KGgoAAAANSU...etc.
I am inserting it already in the database by putting it in a textarea
document.getElementById("TextArea1").value = dataURL;
and in my code behind.
Dim sqlComm As New SqlCommand("INSERT INTO patient_data.dbo.tbPatientImage (HospNum,IdNum,DoctorID,TransDate,PatImage,FileType,FileSize) VALUES (#HospNum,#IDNum,#DoctorID,getdate(),#PatImage,'image/jpg','0')", sqlConn)
Dim photoParam As New SqlParameter("#PatImage", SqlDbType.VarChar)
sqlcomm.photoParam.Value = TextArea1.Value
sqlcomm.Parameters.Add(photoParam)
sqlcomm.ExecuteNonQuery()
Yeah it is inserting but when i try to retrieve it on the database, it does not show anything.
Some files that were inserted by the use of Fileupload were retrieved and displayed correctly, but the inserted data:image/png;base64,iVBORw0KGgoAAAANSU...etc. doesn't work.
What should i do? is there an easier/better way?
I would like to output sql output to an excel file, and a sheet that I give a name to, i.e. not "Sheet1". How do I even begin code this?
Below is current code that reads sql output
$sql_output = #()
while ($rdr.read()){
$sql_output += [PSCustomObject][Ordered]#{
Col1=$rdr.GetValue(0)
Col2=$rdr.GetValue(1)
Col3=$rdr.GetValue(2)
Col4=$rdr.GetValue(3)
Col5=$rdr.GetValue(4)
}
$count=$count + 1
}
Then exports to csv
$sql_output | Export-CSV "D:\Script\Network_Threat_Protection.csv" -NoTypeInfo -Append
I would eventually like this powershell script to read multiple sql queries and output it to different sheets within excel, but let me get the jist of exporting to excel first ....
Export-CSV does not generate an Excel file. It generates a comma delimited text file that usually is set to open with Excel. Being a CSV file there is no knowledge of multiple sheets or dataset properties like sheetnames, for that you will need to use the Excel comobject (and all of its nuances).
Here is a basic example of writing a real Excel file:
$a = New-Object -com Excel.Application
$a.Visible = $True
$b = $a.Workbooks.Add()
$c = $b.Worksheets.Item(1)
$c.Cells.Item(1,1) = "A value in cell A1."
$b.SaveAs("C:\Scripts\Test.xls")
$a.Quit()
What you are trying to do is not new. There are a lot of scripts on the internet for this task. Microsoft's Script Center is a good place to find powershell scripts. Here is one that seems to do what you want.
you can use CPPLUS library for exporting tables to excel sheets..
private DataTable GetData(string tableName)
{
using (SqlConnection sqlCon = new SqlConnection(connectionString))
{
SqlCommand sqlCommand = new SqlCommand("SELECT * FROM " + tableName, sqlCon);
sqlCon.Open();
var reader = sqlCommand.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(reader);
return dt;
}
}
private void SaveExcel(DataTable dataTable, string newFile)
{
using (ExcelPackage pck = new ExcelPackage())
{
ExcelWorksheet ws = pck.Workbook.Worksheets.Add(newFile);
ws.Cells["A1"].LoadFromDataTable(dataTable, true);
pck.SaveAs( new System.IO.FileInfo("d:\\Export\\" + newFile + ".xlsx"));
}
}
Download Source