Category Archives: DataBase

Change MS SQL 2005 login password using sql query

If you want to change the MS Sql 2005 ‘s password then just run the following sql query after logging into query anlyzer

sp_password ‘oldPassword’ , newPassword’

Always use strong SQL passwords (i.e. having uppercase characters , lowercase characters, numeric values, special characters) for security purpose, this way it will be difficult to hack, hard to guess, hard to crack by brute force attacks.

Rename a table Column in MS SQL

How to rename a MS SQL server database table column name after the table creation??
You can rename a column regardless of it is null or contains any data.

We need to use a System stored procedure to rename. Any command with alter keywords won’t work.

EXEC sp_rename ‘tableName.[oldColumnName]’, ‘newColumnName’, ‘COLUMN’

EXEC sp_rename ‘Ultra_tblPressRelease.[uShowStatus]’, ‘uShowInA2B’, ‘COLUMN’

The above line will rename the existing column named uShowStatus of table tblPressRelease to uShowInA2B.

There will be no adverse effect of this procedure on your table data.
But you have to update all your SQL Cursors and Stored Procedures with the new column name (if any).

ASp.Net 2.0 GridView Delete Button Confirmation pop-up

While using GridView in pages wants to confirm the deletion form user. To do this we can take him to another page having GUI to confirm and then delete the record on that page.

Instead of doing so much hardwork you can achieve this on the same page with a little bit of extra code.


Add a client alert script to the delete button of every row.
In the delete event of GridView delete the record.


Page’s Aspx Design File Begins
<asp:GridView ID=”gvFaq” runat=”server” AutoGenerateColumns=”False” CellPadding=”4″
ForeColor=”#333333″ GridLines=”None” OnRowDataBound=”gvFaq_RowDataBound” OnRowDeleting=”gvFaq_RowDeleting”>
<FooterStyle BackColor=”#5D7B9D” Font-Bold=”True” ForeColor=”White” />
<RowStyle BackColor=”#F7F6F3″ ForeColor=”#333333″ />
<asp:BoundField DataField=”slno” HeaderText=”Sl No.” />
<asp:BoundField DataField=”cHeading” HeaderText=”Question” />
<asp:BoundField DataField=”cPosition” HeaderText=”Position” />
<asp:CommandField HeaderText=”Manage” ShowSelectButton=”True” />
<asp:CommandField HeaderText=”Delete” ShowDeleteButton=”True” />
<PagerStyle BackColor=”#284775″ ForeColor=”White” HorizontalAlign=”Center” />
<SelectedRowStyle BackColor=”#E2DED6″ Font-Bold=”True” ForeColor=”#333333″ />
<HeaderStyle BackColor=”#5D7B9D” Font-Bold=”True” ForeColor=”White” />
<EditRowStyle BackColor=”#999999″ />
<AlternatingRowStyle BackColor=”White” ForeColor=”#284775″ />
Page’s Aspx Design File Ends

Database Design FIle

Code Behind File Begins
1) Import Namespaces
using System.Data.SqlClient;

2) Declare global variables which will be used in page
DataSet ds = new DataSet();
SqlDataAdapter da;
SqlConnection myConnection;
String connStr = “your database connection string goes here”‘;
String sql = string.Empty;

3) Page Load event
protected void Page_Load(object sender, EventArgs e)
if (Page.IsPostBack == false)

4) GridView filling method
private void fillGridView()

myConnection = new SqlConnection(connStr);
sql = “select * from tblFaq order by slno desc”;

da = new SqlDataAdapter(sql, myConnection);
da.Fill(ds, “tblFaq”);

gvFaq.DataSource = ds.Tables[0];

catch (Exception ex)

5) In the RowDataBound event add a java script event to the delete cell.
protected void gvFaq_RowDataBound(object sender, GridViewRowEventArgs e)
if (e.Row.RowType == DataControlRowType.DataRow)
e.Row.Cells[4].Attributes.Add(“onClick”, “return confirm(‘Are you sure you want to delete the record?’);”);

6) Handle the RowDeleting event to delete the record of current row.

protected void gvFaq_RowDeleting(object sender, GridViewDeleteEventArgs e)
myConnection = new SqlConnection(connStr);
sql = “delete from tblFaq where slno = ” + Convert.ToInt32(gvFaq.Rows[e.RowIndex].Cells[0].Text);
SqlCommand oldcom = new SqlCommand(sql, myConnection);
Response.Write(“Record Deleted”);
catch (Exception ex)
lblError.Text = ex.Message;

Code Behind File Ends
The output will look like this

For Source Code visit

Update database data using SQL Cursors based on conditions

Recently one of my MSSQL database got SQL Injection attacks.
Hacker put some JavaScript code in all row data to get hits on his website (which is apparently blocked, and soon my site will also be got banned if it keep happening for a long time).

Because the database has a huge amount of data, i can’t update table data using ExecuteNonQuery commands as it will result in a great overload on database and network resources.

So I decided to make something logical which is fast and logical way to handle this situation, and at last i ended up with writing a cursor.

This cursor finds a specific string and replaces it with null.


Create a table with sample data

create table tblDataUpdateTest
slno int identity(1,1),
cName varchar(50),
cRemarks varchar(50),

insert into tblDataUpdateTest (cName, cRemarks) values (‘name1′,’some text here BADCODE’)
insert into tblDataUpdateTest (cName, cRemarks) values (‘name2′,’raBADCODEhul’)
insert into tblDataUpdateTest (cName, cRemarks) values (‘name3′,’dj BADCODEis devil’)

select * from tblDataUpdateTest

Create Cursor to update database table

Declare @@counter int
set @@counter=0
Declare @@slno int
Declare @@cRemarks varchar(100)

Declare tmepTbl cursor
Select slno,cRemarks from tblDataUpdateTest

Open tmepTbl /* Opening the cursor */

fetch next from tmepTbl
into @@slno,@@cRemarks

while @@fetch_Status-1

Update tblDataUpdateTest
set cRemarks = Replace(@@cRemarks,’BADCODE’,”)
where slno = @@slno

fetch next from tmepTbl
into @@slno, @@cRemarks

set @@counter=@@counter+1
close tmepTbl
Deallocate tmepTbl


By running this cursor all the occurrences of BADCODE will be eliminated from the specified table.

I used word BADCODE here but in my actual data it was a java script tag which was creating all the problem.

For more articles updates and sourcecodes please visit dotnetcoderoom

XML Serialization in .Net Framework (Write Xml from Dataset)

Serialization is converting an object to a format in which it can be saved (exported) as file or a physical medium. A simple and basic example would be, if we create an XML from a Dataset it is called Serialization.

DataSet ds = new DataSet();
SqlDataAdapter da;
SqlConnection myConnection;
String connStr = ConfigurationManager.ConnectionStrings[“DatabaseConnectionString1”].ToString();

SqlConnection myConnection = new SqlConnection(connStr);
String sql = “select * from tblCategory”;
da = new SqlDataAdapter(sql, myConnection);
da.Fill(ds, “tblCategory”);
catch (Exception ex)

The above code will write an XML file called info.xml from a Dataset called “ds” into xmls folder in root of website.

Alternatively we can use some advanced options to format the data which is being written.

ds.WriteXml(Server.MapPath(“~/xmls/info.xml”, XmlWriteMode.WriteSchema);

Some options are. Some of the attributes available in Microsoft .Net Framework are as follows:

XmlWriteMode.DiffGram — Writes the entire DataSet as a DiffGram.
XmlWriteMode.IgnoreSchema — Writes the current contents of the DataSet as XML data, without an XML Schema Definition language (XSD) schema.
XmlWriteMode.WriteSchema — Writes the current contents of the DataSet as XML data with the relational structure as inline XSD schema.
For more articles updates and sourcecodes please visit dotnetcoderoom

Read CSV into an Array

Many times we have .csv or .xls files and we need to insert data into database or manipulate it.

Dim reader As Microsoft.VisualBasic.FileIO.TextFieldParser
reader = My.Computer.FileSystem.OpenTextFieldParser _
reader.TextFieldType = Microsoft.VisualBasic.FileIO.FieldType.Delimited
reader.Delimiters = New String() {“,”}
Dim currentRow As String()
While Not reader.EndOfData
currentRow = reader.ReadFields()
Dim currentField As String
For Each currentField In currentRow
Catch ex As Microsoft.VisualBasic.FileIO.MalformedLineException
MsgBox(“Line ” & ex.Message & _
“is not valid and will be skipped.”)
End Try
End While

**End of article**

For more articles updates and sourcecodes please visit dotnetcoderoom

Update Dataset data back to Database

This post explains how to insert, update, and delete data in a Database using Dataset.

The DataSet can be considered an in-memory cache of data retrieved from a database. The DataSet consists of a collection of tables, relationships, and constraints.

Firstly, we have to fill data into a DataSet from Database.
Secondly, when the DataSet is loaded, you can modify the data, and the DataSet will keep track of the changes made bu user.

The Add method of DataTable accepts either an array of the expected data columns, or a DataRow.

(Please note that all code is in c# language)

Step 1: Create a new Connection and SqlDataAdapter
SqlConnection myConnection = new SqlConnection(“connectionStringGoesHere”);
SqlDataAdapter mySqlDataAdapter = new SqlDataAdapter(“Select * from tblNews”, myConnection);
DataSet myDataSet = new DataSet();
DataRow myDataRow;

Step 2: Create SqlCommandBuilder(The SqlDataAdapter does not automatically generate the Transact-SQL statements required to match changes made to a DataSet with SQL Server. But, you can create a SqlCommandBuilder object to automatically generate Transact-SQL statements for single-table updates.)
SqlCommandBuilder mySqlCommandBuilder = new SqlCommandBuilder(mySqlDataAdapter);

// Set the MissingSchemaAction property to AddWithKey because Fill will not cause primary
// key & unique key information to be retrieved unless AddWithKey is specified.
mySqlDataAdapter.MissingSchemaAction = MissingSchemaAction.AddWithKey;

mySqlDataAdapter.Fill(myDataSet, “tblNews”);

Step 3: Add rows to DataTable

myDataRow = myDataSet.Tables[“tblNews”].NewRow();
myDataRow[“cNewsId”] = “NewID”;
myDataRow[“cHeading”] = “New Heading”;
myDataRow[“cContent”] = “Content here”;


Step 4: Editing Row Data
We can change the data in a DataRow by accessing the DataRow. Use the index of the row in the RowsCollection accessed through the Rows property:


Access a specific row by specifying the Primary Key value:

DataRow myDataRow1 = myDataSet.Tables[“tblNews”].Rows.Find(“124”);

Here “124” is the value of the Primary Key “cHeading” in the “tblNews” table.

Step 5: Deleting a record
Use Delete method to delete a Row. All changes are done in dataset until you don’t explicitly update DataSet data to the Database. Use RejectChanges method of DataSet to reverse all changes made to DataSet.


Note: The original and new values are maintained in the row. The RowChanging event allows you to access both original and new values to decide whether you want the edit to proceed.

SqlCommandBuilder mySqlCommandBuilder = new SqlCommandBuilder(mySqlDataAdapter);

Step 6: Finally Update DataBase
To submit the data from the DataSet into the database, use dataAdapter’s Update method.

mySqlDataAdapter.Update(myDataSet, “tblNews”);

A Visual Studio Solution code sample will be coming soon……

**End of article**

For more articles updates and sourcecodes please visit dotnetcoderoom