Saving objects in a SQL Server database - sql

I am trying to include an object of a class created by me in a SQL Server database. I am trying to convert it to VARBINARY, but the method Add doesn't recognize the VARBINARY type. The error I get is:
VARBINARY : undeclared identifier.
I am using namespaces System.Data and System.Data.SqlClient.
Here is my code:
MemoryStream^ memStream = gcnew MemoryStream();
StreamWriter^ sw = gcnew StreamWriter(memStream);
sw-> Write (eyemax);
SqlConnection^ myConnection = gcnew SqlConnection();
myConnection->ConnectionString = "Data Source = (localdb)\\ProjectsV13;AttachDbFilename\=C:\\Users\\Usuario\\AppData\\Local\\Microsoft\\VisualStudio\\SSDT\\TUKDatabase.mdf; Integrated Security = True; Connect Timeout = 30";
myConnection->Open();
SqlCommand^ cmd = gcnew SqlCommand("INSERT INTO Features(Face,Eye) VALUES (#face, #eye)",myConnection);
cmd->Parameters->AddWithValue("#face", face);
cmd->Parameters->Add("#eye",SqlDbType(VarBinary));
cmd->Parameters["#eye"]->Value = memStream->GetBuffer();

Related

Can I store difference file types into SQL Server database?

I have created a vb.net project and a SQL Server database, I want to store my other created projects to the database with some of there description. I don't know can I do that or I can store my projects files into the database in the first place. I wanted to compress my projects files to a zip file and then store the zip file to the database but I don't know if I can store these files to the database which includes a lot of file types like (jar, java, sln, vb, c#, txt ...etc)?
Thanks for your help.
Yes, you can store files in a SQL Server database table. I highly recommend you to compress them into a zip file.
First step is to create a table:
CREATE TABLE Files
(
Id INT IDENTITY PRIMARY KEY,
FileData VARBINARY(MAX) FILESTREAM NULL,
Name NVARCHAR(300)
)
and then open your zip file as stream and Insert it into your table.
OpenFileDialog openFileDlg = new OpenFileDialog();
openFileDlg.InitialDirectory = Directory.GetCurrentDirectory();
if (openFileDlg.ShowDialog() == DialogResult.OK)
{
FileInfo fi = new FileInfo(openFileDlg.FileName);
FileStream fs = new FileStream(fi.FullName, FileMode.Open, FileAccess.Read);
BinaryReader rdr = new BinaryReader(fs);
byte[] fileData = rdr.ReadBytes((int)fs.Length);
rdr.Close();
fs.Close();
string cs = #"Data Source=<your server>;Initial Catalog=MyFsDb;Integrated Security=TRUE";
using (SqlConnection con = new SqlConnection(cs))
{
con.Open();
string sql = "INSERT INTO Files VALUES (#Data, #Name)";
SqlCommand cmd = new SqlCommand(sql, con);
cmd.Parameters.Add("#Data", SqlDbType.Image, fileData.Length).Value = fileData;
cmd.Parameters.Add("#Name", SqlDbType.NVarChar).Value = fi.Name;
cmd.ExecuteNonQuery();
con.Close();
}
MessageBox.Show(fi.FullName, "File Inserted!", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
Source : MSDN

How to save the SQL Server table xml column data in physical path as .xml format?

I have an sql server database table which has xml column name called "MESSAGE" and which will store xml data.
The database table look like,
Now I need to get this "MESSAGE" column data and save into System physical path as xml file(Ex: test.xml etc.,)
Any suggestion how to implement this using c#.net?
You could try something like this (using plain ADO.NET and a very basic SQL query):
static void Main(string[] args)
{
// get connection string from app./web.config
string connectionString = "server=.;database=yourDB;Integrated Security=SSPI;";
// define query
string query = "SELECT MESSAGE FROM dbo.SamTest WHERE ID = 1;";
// set up connection and command
using (SqlConnection conn = new SqlConnection(connectionString))
using (SqlCommand selectCmd = new SqlCommand(query, conn))
{
// open connection, execute query to get XML, close connection
conn.Open();
string xmlContents = selectCmd.ExecuteScalar().ToString();
conn.Close();
// define target file name
string targetFileName = #"C:\tmp\test.xml";
// write XML out to file
File.WriteAllText(targetFileName, xmlContents);
}
}

Sql Bulk Copy Cannot access destination table

I'm trying to read data from files and to use bulk copy to insert it in the database table.
When I try to run my code, I get the error: "Cannot Access Denstination Table"
Declaration of FlatTable.
System.Data.DataTable flatTableTempData = new System.Data.DataTable("FlatTable");
DataColumn DistrictColumn = new DataColumn();
DistrictColumn.ColumnName = "DistrictName";
// Create Column 3: TotalSales
DataColumn TownColumn = new DataColumn();
TownColumn.ColumnName = "TownName";
DataColumn FarmerColumn = new DataColumn();
FarmerColumn.ColumnName = "FarmerName";
flatTableTempData.Columns.Add(DistrictColumn);
flatTableTempData.Columns.Add(TownColumn);
flatTableTempData.Columns.Add(FarmerColumn);
This is my code, with the connection string and the insertion using bulk copy:
using (SqlConnection con = new SqlConnection("Data Source=DRTARIQ-PC\\SQLEXPRESS;Integrated Security=SSPI;Initial Catalog=TestDB2"))
{
con.Open();
using (SqlBulkCopy s = new SqlBulkCopy(con))
{
s.DestinationTableName = flatTableTempData.TableName;
foreach (var column in flatTableTempData.Columns)
s.ColumnMappings.Add(column.ToString(), column.ToString());
s.BulkCopyTimeout = 500;
s.WriteToServer(flatTableTempData);
}
}
I've encountered the same problem. The table exists, the SQL user has access but SqlBulkCopy cannot access the table. My problem turned out to be I turned off the indexing to try and insert faster (rebuild index after the bulkcopy), but this made the table inaccessible. After I turned the indexing on again it worked, SqlBulkCopy has access to the table.
The table name in WriteToServer method of SqlBulkCopy must be surrounded with [ ] signs.

vb.net get result of sql statement

Hello take a look at the code below:
Try
con.ConnectionString = strCon
Dim strCommand as String = "RESTORE FILELISTONLY
FROM DISK = 'C:\AdventureWorks.BAK'
WITH FILE = 1
GO"
Dim cm As New SqlClient.SqlCommand(strCommand, con)
con.Open()
cm.ExecuteNonQuery()
Does anyone know how to get the list of logical files for my database, it does not work with executereader. i want to get the mdf and ldf files name for my database backup file.
Thanks.
As I've said before - the GO is NOT a T-SQL keyword - drop that!
And secondly, you don't need a WITH FILE when restoring only the file headers - try this:
Dim strCommand as String = "RESTORE FILELISTONLY
FROM DISK = 'C:\AdventureWorks.BAK'"
This will return several pieces of data - so you need to deal with a result set and thus use .ExecuteReader() to get this data from the query.
Try this code (it's C#, but should be easy enough to convert to VB.NET):
using System;
using System.Data;
using System.Data.SqlClient;
namespace GetPhysicalDbNames
{
class Program
{
static void Main(string[] args)
{
string stmt = #"RESTORE FILELISTONLY FROM DISK = 'D:\temp\AW2012.BAK'";
using (SqlConnection conn = new SqlConnection("server=.;database=master;integrated Security=SSPI"))
using (SqlCommand cmd = new SqlCommand(stmt, conn))
{
DataTable tblInfo = new DataTable();
SqlDataAdapter dap = new SqlDataAdapter(cmd);
dap.Fill(tblInfo);
foreach (DataRow row in tblInfo.Rows)
{
Console.WriteLine("Logical name: {0}", row["LogicalName"]);
Console.WriteLine("Physical file name: {0}", row["PhysicalName"]);
}
}
}
}
}
Executing that RESTORE command returns a result set, which contains among other two columns LogicalName and PhysicalName (which is the actual, complete physical file name of the .mdf and .ldf files)

SQL exception was unhandled in c#

When I want to debug this code it gives error on objConnection.Open():
sqlExeption was Unhandled and say(A
network-related or instance-specific
error occurred while establishing a
connection to SQL Server. The server
was not found or was not accessible.
Verify that the instance name is
correct and that SQL Server is
configured to allow remote
connections. (provider: Named Pipes
Provider, error: 40 - Could not open a
connection to SQL Server))
SqlConnection objConnection = new SqlConnection(
"server=localhost;database=pubs;" +
"user id=sa;password=");
SqlDataAdapter objDataAdapter = new SqlDataAdapter();
DataSet objDataSet = new DataSet();
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
// Set the SelectCommand properties...
objDataAdapter.SelectCommand = new SqlCommand();
objDataAdapter.SelectCommand.Connection =
objConnection;
objDataAdapter.SelectCommand.CommandText =
"SELECT au_lname, au_fname, title, price " +
"FROM authors " +
"JOIN titleauthor ON authors.au_id = " +
"titleauthor.au_id " +
"JOIN titles ON titleauthor.title_id = " +
"titles.title_id " +
"ORDER BY au_lname, au_fname";
objDataAdapter.SelectCommand.CommandType =
CommandType.Text;
// Open the database connection...
**objConnection.Open();**
// Fill the DataSet object with data...
objDataAdapter.Fill(objDataSet, "authors");
// Close the database connection...
objConnection.Close();
// Set the DataGridView properties
// to bind it to our data...
grdAuthorTitles.AutoGenerateColumns = true;
grdAuthorTitles.DataSource = objDataSet;
grdAuthorTitles.DataMember = "authors";
// Clean up
objDataAdapter = null;
objConnection = null;
}
This error typically occurs when your server name is wrong or the sql server is not on.
localhost and (local) are treated differently for sql server. You might want to try (local).
Here's a list of connection strings to help you out.
If you are using sql express then you might want to change it from localhost to .\sqlexpress.
To check that your SQL Server is on be sure the services for it are on. You can do this in services and also in the Configuration Manager.
First of all, with the SqlDataAdapter, you don't need to specifically open and close the SqlConnection yourself - the adapter will do that for you.
Secondly, I'd strongly recommend putting all your ADO.NET code into using(.....) { .... } blocks as a best practise.
Furthermore, on your local PC, typically you don't need to specify a specific user for your database, but you can use the built-in Windows authentication directly (integrated security=SSPI) in your SQL connection string.
And as a last thing: if you don't need multiple tables in your DataSet, it's easier and better to use DataTable instead - less overhead, less performance penalties. No need to specify table names as data members and so forth. Just plain easier.
Try this code:
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
using(SqlConnection objConnection = new SqlConnection("server=(local);database=pubs;integrated security=SSPI;"))
{
SqlDataAdapter objDataAdapter = new SqlDataAdapter();
// Set the SelectCommand properties...
objDataAdapter.SelectCommand = new SqlCommand();
objDataAdapter.SelectCommand.Connection = objConnection;
objDataAdapter.SelectCommand.CommandText =
"SELECT au_lname, au_fname, title, price FROM authors " +
"JOIN titleauthor ON authors.au_id = titleauthor.au_id " +
"JOIN titles ON titleauthor.title_id = titles.title_id " +
"ORDER BY au_lname, au_fname";
DataTable tblData = new DataTable();
// Fill the DataSet object with data...
objDataAdapter.Fill(tblData);
// Set the DataGridView properties
// to bind it to our data...
grdAuthorTitles.AutoGenerateColumns = true;
grdAuthorTitles.DataSource = tblData;
}
}
That way, disposal of the referenced classes will be handled automatically for you.