Saturday, June 25, 2005

A bit of preliminary C#

Things to be done,

1. Read a text file.
2. Insert only the first entry for the user in a Database table.
3. Run analysis services for clustering results

Text files are read and written through the StreamReader and StreamWriter classes. There are various ways to create instances of these classes—for example,

string file_name = @"C:\fictions\gnome.txt";

StreamReader freader = File.OpenText( file_name );
StreamWriter fwriter =
File.CreateText( @"C:\fictions\gnome.diag" );

 string text_line;
while (( text_line = freader.ReadLine() ) != null )
{
// Instead of this I want to insert it in a database table
// write to output file
fwriter.WriteLine( text_line );
}

// must explicitly close the readers
freader.Close();
fwriter.Close();


How do i do SQL Server programming usin C# ( did it before but forgot .. :) )
From c-sharpcorner.com
using System;
using System.Data;
using System.Data.SqlClient;

namespace SimpleSql1
{
class Insert
{
[STAThread]
static void Main(string[] args)
{
SqlConnection conn = new SqlConnection("Data Source=Computername;"+ // TODO: change comp name
"Initial Catalog=simplesql;"+
"User ID=sa;"+
"Password=pass;");

string strText = Console.ReadLine();

try
{
SqlCommand cmd = new SqlCommand();
cmd.CommandTimeout = 60;
cmd.Connection = conn;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT Count(*) FROM simplesql";// Couldn't do it without sorry

conn.Open();
if (conn.State == ConnectionState.Open)
{
object objCount = cmd.ExecuteScalar();
int iCount = (int) objCount;
Console.WriteLine("Count was succesfull");

cmd.CommandText = "INSERT INTO simplesql (simple_id, simple_text) VALUES ("+
iCount +",'"+ strText +"')";
cmd.ExecuteScalar();
Console.WriteLine("Succesfully inserted the string");
}
}
catch (Exception exp)
{
Console.Write(exp.Message);
}
finally
{
conn.Close();
}

Console.WriteLine("\n\n Press any key to quite");
Console.Read();
}
}
}

No comments: