Save RTF data in My Sql database - vb.net

Please tell me how to save and show Richtextbox's data in database and retrive it in saved format and which datatype should be used to save that data. i am using vb.net and MY SQL

if your data contains image/icons or some special symbols then its better to go for BLOB otherwise you can go with varchar datatype.

You can use the BLOB datatype.

Your RTF Data feild should be "Memo".
private void InsertToMemo()
{
using (OleDbConnection oleDbConn = new OleDbConnection(#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\AD.mdb"))
{
OleDbCommand oleDbCmd = new OleDbCommand("insert into Table2 values(1,'" + this.richTextBox1.Rtf + "')", oleDbConn);
oleDbCmd.Connection.Open();
oleDbCmd.ExecuteNonQuery();
}
}
private void ReadFormMemo()
{
using (OleDbConnection oleDbConn = new OleDbConnection(#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\AD.mdb"))
{
OleDbCommand oleDbCmd = new OleDbCommand("select Field1 from Table2", oleDbConn);
oleDbCmd.Connection.Open();
OleDbDataReader oleDbDataReader = oleDbCmd.ExecuteReader();
oleDbDataReader.Read();
this.richTextBox2.Rtf = oleDbDataReader.GetString(0);
}
}

Related

Insert Dataset Table records to SQLite table - in VB.NET

I've found this answer in C (Or C# maybe), but I don't really understand C. I'm a vb guy (and new to .net). Can anyone give me a hand in converting this to vb?
The concept appears to be exactly what I need:
I've got an Excel worksheet loaded to a dataset table.
I have an identical table in the SQLite db (column for column).
I want to save the imported Worksheet data in the dataset table to the empty SQLite table.
Here is the code from the link:
SQLiteConnection m_dbConnection;
void createDbAndTable()
{
SQLiteConnection.CreateFile("MyDatabase.sqlite");
m_dbConnection = new SQLiteConnection("Data Source=MyDatabase.sqlite; Version=3;");
m_dbConnection.Open();
string sql = "create table myValues (name varchar(20), highScore int)";
SQLiteCommand command = new SQLiteCommand(sql, m_dbConnection);
command.ExecuteNonQuery();
}
void fillTable(DataSet ds)
{
var dt = ds.Tables[0];
foreach (DataRow dr in dt.Rows)
{
var name = dr["name"].ToString();
var score = Convert.ToInt32(dr["value"].ToString());
string sql = "insert into myValues (name, highScore) values ( '" + name + "'," + score + ")";
SQLiteCommand command = new SQLiteCommand(sql, m_dbConnection);
command.ExecuteNonQuery();
}
m_dbConnection.Close();
}
Any help would be greatly appreciated!

How do I cast decimal values to string from my database?

The below code snippet pulls a pack size column from my table but am using getString which I get an error then now see is an issue because the column am pulling is of decimal type. How would I cast my snippet to accept the decimal values?
try
{
string connectionString = "Data Source=CMDLAP121\\SQLEXPRESS;Initial Catalog=TESTBAR;Integrated Security=True";
string query = "SELECT * FROM BCODEREF WHERE BAR_CODE = '" + comboBox1.Text + "';";
string mystring = query;
SqlConnection con = new SqlConnection(connectionString);
con.Open();
SqlCommand cmd = new SqlCommand(query, con);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
string spo = dr.GetString(dr.GetOrdinal("PACKSIZE"));
ponum.Text = spo;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
Parse to decimal first and convert to a string with the format you need:
decimal packSize= 0;
decimal.TryParse(dr["PACKSIZE"].ToString(), out packSize);
ponum.Text = packSize.ToString("0.00"); //specify format you need
See this post for details of how to set up appropriate string format

Send data from one data table to other

I am trying to send data from sql to oracle using bulk copy.
Here is the code
string sqldb = "server=DOR-SQLTEST\\DORSQLSERVER;" + "initial catalog=RD2KTEST;" + "user id=amehra;" + "password=Research#322";
SqlConnection sqlconn = new SqlConnection(sqldb);
sqlconn.Open();
string sqlstring="select TOP 10 POSITION_ID, POSITION_DESC from T_CD_POSITION";
SqlCommand scmd = new SqlCommand(sqlstring, sqlconn);
SqlDataReader reader = scmd.ExecuteReader();
while(reader.Read())
{
Console.WriteLine("entered to write to oracle.......\n\n");
string oradb = "Data Source=UHAMPTST;user id=ocg_de;password=rd2k";
OracleConnection oraconn = new OracleConnection(oradb);
oraconn.Open();
Console.WriteLine("orca conn established....");
using( OracleBulkCopy orca_bulk_copy = new OracleBulkCopy(oraconn))
{
orca_bulk_copy.DestinationTableName = "t_test_postion";
orca_bulk_copy.WriteToServer(reader);//line 38
orca_bulk_copy.Close();
orca_bulk_copy.Dispose();
}
}
}
}
}
I'm getting error at line 38 as Oracle Exception occurred.
Kindly rectify the problem

Closing Excel file after reading

Here is my code for opening the Excel file and reading the data, everything is working fine but what I would like is to close once the Excel file is read, how would i do that? I try Dispose the object but did not help.
public static DataTable ExcelWorkbook(string workbookName)
{
string connectionString = String.Format(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=""Excel 8.0;HDR=YES;IMEX=1;""", FILENAME);
string query = String.Format("select * from [{0}$]", workbookName);
OleDbDataAdapter dataAdapter = new OleDbDataAdapter(query, connectionString);
DataSet dataSet = new DataSet();
dataAdapter.Fill(dataSet);
dataAdapter.Dispose();
DataTable myTable = dataSet.Tables[0];
if (myTable != null)
return myTable;
return null;
}
Your code should look sth like that:
OleDbConnection connection;
OleDbDataAdapter clientsAdapter new OleDbDataAdapter();
DataSet myDataSet = new DataSet();
connectionString = (#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0}.xlsx;Extended Properties=""Excel 12.0 Xml;HDR=YES""",FILENAME);
connection = new OleDbConnection(connectionString);
connection.Open();
clientsAdapter.SelectCommand = new OleDbCommand("SELECT * FROM [{0}$]", connection);
DataTable data = new DataTable("MyTable");
clientsAdapter.Fill(data);
myDataSet.Tables.Add(data);
connection.Close();
After the connection is closed, the excel file will be unlocked.
You are disposing the data adapter that read the data, not the reference to the Excel file itself.
Somewhere in your code, you will have opened the workbook. You need to call
workbook.Close();
http://msdn.microsoft.com/en-us/library/microsoft.office.interop.excel.workbookclass.close(v=office.14).aspx

SqlCommand.ExecuteScalar - specify a particular data item

I have a Stored Procedure which returns 10 columns of data. Using cmd.ExecuteScalar() returns the value of the 1st column from the 1st record.
How can I change this so that I can return different columns, by specifying their alias/dataitem name?
I want to be able to do something like:
Dim FirstName as String = cmd.ExecuteScalar("FirstName")
You could create a method that calls ExecuteReader, and then uses GetOrdinal with your column name to then call GetString.
My VB is non-existent, but this is the C# for an extension method.
public static class SqlCommandExt
{
public static string ExecuteScalar(this SqlCommand cmd, string columnName)
{
using (var reader = cmd.ExecuteReader())
{
if (!reader.Read())
return null;
var index = reader.GetOrdinal(columnName);
return reader.GetString(index);
}
}
}
You can not. Command.ExecuteScalar take no parameters ..
What you can do is to use a text command and modify its CommandText property value to include the column you need to get:
command.CommandText = "SELECT " + columnName + " FROM Table WHERE Key = " + ...
You could create an extension method to do this for you. C# equiv (which I imagine you could translate to a VB.NET extension rather easily):
public static T ExecuteScalar<T>(this SqlCommand cmd, String columnName)
{
using(var reader = cmd.ExecuteReader())
{
var item = default(T);
if(reader.Read())
{
item = (T)dataReader.GetValue(dataReader.GetOrdinal(columnName))
}
return item;
}
}
... and invoke it like so:
var firstName = cmd.ExecuteScalar<String>("FirstName");
You should try the below code also.
Private Sub YourFunctionName()
Using con As System.Data.SqlClient.SqlConnection = New SqlConnection("YourConnection string")
con.Open()
Using cmd As SqlCommand = New SqlCommand
Dim expression As String = "Parameter value"
cmd.CommandType = CommandType.StoredProcedure
cmd.CommandText = "Your Stored Procedure"
cmd.Parameters.Add("Your Parameter Name", SqlDbType.VarChar).Value = expression
cmd.Connection = con
Using dr As IDataReader = cmd.ExecuteReader()
If dr.Read() Then
Dim str As String = dr("YourColumnName").ToString()
End If
End Using
End Using
End Using
End Sub