Run sp_msforeachdb to select dbsize used in c# - asp.net

I have a query as such:
EXEC sp_msforeachdb
'USE [?];
SELECT DB_NAME() AS [Database Name],
CAST(SUM(FILEPROPERTY(name, ''SpaceUsed''))/128.0 AS decimal(18,2)) AS [Used space(MB)]
FROM sys.database_files
Where type_desc = ''ROWS'' and
GROUP BY type_desc'
and executing this in MSSM is alright.
My problem is that I need to execute this in my application using c# and stored in a Datatable. Any idea how to do this?
Tried looking for at CommandType.StoredProcedure and CommandType.Textbut still can't figure it out.
FYI, I'm not allowed to create a new stored procedure for this.
EDIT (SAMPLE CODE)
using (SqlConnection sqlConnection = new SqlConnection(HoustonSqlCon))
{
const string query = "EXEC sp_msforeachdb 'USE [?]; SELECT DB_NAME() AS[Database Name]," +
"CAST(SUM(FILEPROPERTY(name, ''SpaceUsed'')) / 128.0 AS decimal(18, 2)) AS[Used space(MB)]" +
"FROM sys.database_files" +
"Where type_desc = ''ROWS''" +
"GROUP BY type_desc'";
using (SqlCommand comm = new SqlCommand(query, sqlConnection))
{
sqlConnection.Open();
comm.CommandType = CommandType.Text;
SqlDataAdapter adapter = new SqlDataAdapter();
adapter.Fill(totalSchemas);
}
}

Related

Can't Update Database from ASP.NET Webform

I can't get an ASP.NET webform to update a database. I'm trying to edit an existing record in the database. The webform populates the data from the record into the form. The user then changes data and updates the record in the database when the form is submitted.
The problem is that nothing is changed in the database when a modified form is submitted. What am I doing wrong here? The SQL works in MSSQL Management Studio.
Thanks.
private void SaveToDatabase ()
{
using (SqlConnection conn = new SqlConnection (_connectionString_Bluebook))
{
conn.Open ();
string sql = #"update Companies
set CompanyName=#CompanyName, AccountNo=#AccountNo
where AccountNo=" + _accountNo;
using (SqlCommand command = new SqlCommand (sql, conn))
{
command.Parameters.Add (new SqlParameter ("#CompanyName", TextBox_CompanyName.Text));
command.Parameters.Add (new SqlParameter ("#AccountNo", TextBox_Account.Text));
command.ExecuteNonQuery ();
}
conn.Close ();
}
}
Try adding a parameter for the original account number to your query. The example below uses strongly-typed parameters for security and performance, taking a guess at your actual SQL data types and column lengths, which you should change to your actual definitions.
private void SaveToDatabase()
{
using (SqlConnection conn = new SqlConnection(_connectionString_Bluebook))
{
conn.Open();
string sql = #"update dbo.Companies
set CompanyName=#CompanyName, AccountNo=#AccountNo
where AccountNo=#OriginalAccountNo;
IF ##ROWCOUNT = 0 RAISERROR('Account number %s not found',16,1,#OriginalAccountNo)";
using (SqlCommand command = new SqlCommand(sql, conn))
{
command.Parameters.Add(new SqlParameter("#CompanyName",SqlDbType.VarChar,100).Value = TextBox_CompanyName.Text;
command.Parameters.Add(new SqlParameter("#AccountNo", SqlDbType.Char, 10).Value = TextBox_Account.Text;
command.Parameters.Add(new SqlParameter("#OriginalAccountNo", SqlDbType.Char, 10).Value = _accountNo;
command.ExecuteNonQuery();
}
}
}
If the row is still not updated as expected, make sure _accountNo contains the proper value.
EDIT:
I added a RAISERROR statement to the SQL batch to facilitate this, which you could leave in the code if the not found condition should never occur.
If the SQL Params are not working, then try this way:
comm = new SqlCommand("update student_detail set s_name= '" + txtname.Text + "', age= "+txtage.Text+" , course=' " + txtcourse.Text + "' where roll_no = " + txtrn.Text + " ", conn);
Try to place the debugger and provide the exact error of the compiler

multiple SQL commands. Good style?

I got an asp.net application running perfectly fine. in my code i have the following lines
using (SqlConnection con = new SqlConnection(CS))
{
SqlCommand getGenreId = new SqlCommand("Select ID from tblGenre WHERE Genre=#newGenre;", con);
getGenreId.Parameters.AddWithValue(#"newGenre", newGenre);
SqlCommand cmd = new SqlCommand("UPDATE tblSong SET Title=#newTitle, ArtistId=#newArtistId, GenreId=#newGenreId WHERE (ID = #songId);", con);
cmd.Parameters.AddWithValue(#"newTitle", newTitle);
cmd.Parameters.AddWithValue(#"newArtistId", newArtistId);
cmd.Parameters.AddWithValue(#"songId", songId);
con.Open();
newGenreId = (int)getGenreId.ExecuteScalar();
cmd.Parameters.AddWithValue(#"newGenreId", newGenreId);
cmd.ExecuteNonQuery();
}
i know database connections are valuable resources and i should be careful when using them. (open as late as possible and make sure they will be closed aswell)
My question now is this code considered bad style because im opening the connection then have as sql query to get an ID and then have another sql query to insert a record.
thanks you!
If you convert to using stored procedure, you can eliminate 1 round trip, therefore reducing network traffic and possibly increase performance.
using (SqlCommand cmd = new SqlCommand("Update_tblSong", con);
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#newGenre", newGenre);
cmd.Parameters.AddWithValue("#newTitle", newTitle);
cmd.Parameters.AddWithValue("#newArtistId", newArtistId);
cmd.Parameters.AddWithValue("#songId", songId);
cmd.ExecuteNonQuery();
}
Proc will be like this, I estimated on your variable size.
CREATE PROC Update_tblSong
(
#newGenre VARCHAR(25)
,#newTitle VARCHAR(50)
,#newArtistID INT
,#songID INT
)
AS
BEGIN
SET NOCOUNT ON;
DECLARE #NewGenreID INT;
SELECT #NewGenreID = ID
FROM tblGenre
WHERE Genre = #newGenre;
UPDATE tblSong
SET Title = #newTitle
,ArtistId = #newArtistId
,GenreId = #NewGenreID
WHERE ( ID = #songId )
END;
Overall your code flow seems fine, you are using a single connection to execute multiple (related) commands.
You can improve it further with enclosing your command objects in using statement. Since they implement IDisposable interface, just like your connection object.
using (SqlConnection con = new SqlConnection(CS))
{
con.Open();
using (SqlCommand getGenreId = new SqlCommand("Select ID from tblGenre WHERE Genre=#newGenre;", con))
{
getGenreId.Parameters.AddWithValue(#"newGenre", newGenre);
newGenreId = (int)getGenreId.ExecuteScalar();
}
using (SqlCommand cmd = new SqlCommand("UPDATE tblSong SET Title=#newTitle, ArtistId=#newArtistId, GenreId=#newGenreId WHERE (ID = #songId);", con))
{
cmd.Parameters.AddWithValue(#"newTitle", newTitle);
cmd.Parameters.AddWithValue(#"newArtistId", newArtistId);
cmd.Parameters.AddWithValue(#"songId", songId);
cmd.Parameters.AddWithValue(#"newGenreId", newGenreId);
cmd.ExecuteNonQuery();
}
}
Why not use a single query with a subquery for your SQL?
UPDATE tblSong SET Title = #newTitle, ArtistId = #newArtistId, GenreId = (Select top 1 ID from tblGenre WHERE Genre=#newGenre ORDER BY Genre) WHERE (ID = #songId);

asp.net how to decrypt each label value in a gridview

i have an gridview that retrieves the data via a datatable like this:
protected DataTable allClients()
{
string conn, comm, tSub, tMain;
tSub = "client_sub";
tMain = "client_main";
conn = ConfigurationManager.ConnectionStrings["localsqlserver"].ConnectionString;
comm = "SELECT * FROM [" + tSub + "] t1 LEFT JOIN [" + tMain + "] t2 ON " +
"t1.customer_ID = t2.customer_ID";
SqlConnection connection = new SqlConnection(conn);
SqlCommand cmd = new SqlCommand(comm, connection);
connection.Open();
DataTable allTable = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(allTable);
connection.Close();
return allTable;
}
clientGrid.DataSource = allClients();
clientGrid.DataBind();
and its working fine on retrieving the data but the problem is i am trying to decrypt the value on retrieving it.
i used this encryptor class
so how can decrypt the value of each row in the gridview.
using asp.net 4.0, thanks
Two options - you can loop around the data table in your allClients() method before returning it, or you can look into handling the row bound events when you do the data bind on the grid view - this would allow you to access each row as its created in the grid view and manipulate the data displayed.

Use a variable in update statement ASP.NET in SQL

I want to use variable name as column name in ASP.NET column name.
I'm getting the following error:
Incorrect syntax near 'February'.
The code is
SqlConnection MyConn = new SqlConnection(#"Data Source=.\SQLEXPRESS;AttachDbFilename=E:\apptitude\projects\database\App_Data\Database.mdf;Integrated Security=True;User Instance=True");
MyConn.Open();
int i,n=5;
String[] month=new String[12]{"January","February","March","April","May","June","July","August","September","Octomber","November","December"};
int day = DateTime.Now.Day;
int mon= DateTime.Now.Month;
Label1.Text = day.ToString();
if (day==1)
{
//for(i=1;i<=n;i++)
//{
//Label1.Text = "hi";
int j = 1;
SqlCommand cmd = new SqlCommand();
cmd.Connection = MyConn;
cmd.CommandText = "update Yearly_data set **'"+month[mon]+"'=20";**
i = cmd.ExecuteNonQuery();
Label1.Text = i.ToString();
}
You don't need to enclose column names in single quotes ('); hence this:
update Yearly_data set 'February'=20
Should be written as
update Yearly_data set February=20
If you change your code to the below, it will work:
cmd.CommandText = "update Yearly_data set "+month[mon]+"=20";
However, note that building Dynamic SQL statements is something that should be carefully done as not to risk your app on a SQL Injection attack.
If every month of the year is a ColumnName in Yearly_data then change your line of code to:
cmd.CommandText = "update Yearly_data set ["+month[mon]+"]=20";
In addition to the answers already given, the framework provides a way to get the name of the month using the DateTimeFormatInfo.GetMonthName function.
static string GetMonthName(DateTime sourceDate)
{
var dateFormatInfo = new DateTimeFormatInfo();
return dateFormatInfo.GetMonthName(sourceDate.Month);
}
cmd.CommandText = String.Format("update Yearly_data set {0} = 20", GetMonthName(DateTime.Now));

how to run two queries using the code snippet below?

How to Run two Update Sql Queries using this Sql Snippet ?
The code mentioned below is updating values only in one table .... i want to update data in two different tables using the code mentioned below :
can anybody reedit this code ?
Try
Using conn = New SqlConnection(constr)
Using cmd = conn.CreateCommand()
conn.Open()
Dim sql As String =
"UPDATE a1_ticket
SET Ticket_no =#ticketNo,
BANK = #bank,
PAID = #paid,
BID = #bid
WHERE ITC = #ticketNo"
cmd.CommandText = sql
cmd.Parameters.AddWithValue("#bank", Literal20.Text)
cmd.Parameters.AddWithValue("#paid", Label1.Text)
cmd.Parameters.AddWithValue("#bid", Literal21.Text)
cmd.Parameters.AddWithValue("#ticketNo", Literal3.Text)
cmd.ExecuteNonQuery()
End Using
End Using
Catch ex As Exception
Response.Write(ex.Message)
End Try
Create a Stored Procedure that updates the two tables and execute it using a StoredProcedure Command...
command.CommandType = CommandType.StoredProcedure;
command.CommandText = "UpdateTheTwoTables";
....
Modify the SQL statement to update the two tables.
Using a Stored Procedure is the cleanest way code wise. If you don't feel comfortable doing it like that, I'm sure you can do it like this:
Try
Using conn = New SqlConnection(constr)
Using cmd = conn.CreateCommand()
conn.Open()
Dim sql As String = "UPDATE a1_ticket SET Ticket_no =#ticketNo, BANK = #bank, PAID = #paid, BID = #bid WHERE ITC = #ticketNo"
cmd.CommandText = sql
cmd.Parameters.AddWithValue("#bank", Literal20.Text)
cmd.Parameters.AddWithValue("#paid", Label1.Text)
cmd.Parameters.AddWithValue("#bid", Literal21.Text)
cmd.Parameters.AddWithValue("#ticketNo", Literal3.Text)
cmd.ExecuteNonQuery()
End Using
//
Using cmd = conn.CreateCommand()
conn.Open()
Dim sql As String = "UPDATE a2_ticket SET Ticket_no =#ticketNo, BANK = #bank, PAID = #paid, BID = #bid WHERE ITC = #ticketNo"
cmd.CommandText = sql
cmd.Parameters.AddWithValue("#bank", Literal20.Text)
cmd.Parameters.AddWithValue("#paid", Label1.Text)
cmd.Parameters.AddWithValue("#bid", Literal21.Text)
cmd.Parameters.AddWithValue("#ticketNo", Literal3.Text)
cmd.ExecuteNonQuery()
End Using
End Using
Catch ex As Exception
Response.Write(ex.Message)
End Try
It's a sketch of what I'm trying to say, you may want to change a few things here and there, but the point is you can just update your two tables one after the other. It's not possible in one update statement afaik.
you can also use
Dim sql As String = # "Query for first update;
Query for second update;";
Well as you havent said anything about the second table, or the data you're sending it. I havent put this through the compiler to verify it, but the concept I'd suggest would be
You could do:
void UpdateDB(String sql, String[][] params)
{
Try
{
SqlConnection conn = New SqlConnection(constr);
SqlCommand cmd = conn.CreateCommand();
conn.Open();
cmd.CommandText = sql;
for(int i=0; i<params.length; i++)
{
cmd.Parameters.AddWithValue(params[i,0] params[i,1]);
}
cmd.ExecuteNonQuery();
}
Catch (Exception ex)
{
Response.Write(ex.Message);
}
}
eg send the SQL and the parameters to the function and have it do all the work..

Resources