Posts Tagged ‘SQL’

Code in C# to create a backup of a database in SQL server and restore it

Wednesday, August 19th, 2009

Here they left a code in C # very useful when making your applications with databases in SQL server can support the database and restore it.

Support code for a button:

private void btnBackUp_Click(object sender, EventArgs e)
{
    bool bBackUpStatus = true;

    Cursor.Current = Cursors.WaitCursor; 

     if (Directory.Exists(@"c:\SQLBackup"))
        {
            if (File.Exists(@"c:\SQLBackup\wcBackUp1.bak"))
            {
                if (MessageBox.Show(@"Do you want to replace it?", "Back", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                {
                    File.Delete(@"c:\SQLBackup\wcBackUp1.bak");
                }
                else
                    bBackUpStatus = false;
            }
        }
        else
            Directory.CreateDirectory(@"c:\SQLBackup");

        if (bFileStatus)
        {
            //Connect to DB
            SqlConnection connect;
            string con = "Data Source = localhost; Initial Catalog=dbWiseCodes ;Integrated Security = True;";
            connect = new SqlConnection(con);
            connect.Open();
            //----------------------------------------------------------------------------------------------------

            //Execute SQL---------------
            SqlCommand command;
            command = new SqlCommand(@"backup database dbWiseCodes to disk ='c:\SQLBackup\wcBackUp1.bak' with init,stats=10", connect);
            command.ExecuteNonQuery();
            //-------------------------------------------------------------------------------------------------------------------------------

            connect.Close();

            MessageBox.Show("The support of the database was successfully performed", "Back", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
}

Code for a button to restore:


private void btnRestore_Click(object sender, EventArgs e)
{

    Cursor.Current = Cursors.WaitCursor;

    try
    {
        if (File.Exists(@"c:\SQLBackup\wcBackUp1.bak"))
        {
            if (MessageBox.Show("Are you sure you restore?", "Back", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
            {
                //Connect SQL-----------
                SqlConnection connect;
                string con = "Data Source = localhost; Initial Catalog=master ;Integrated Security = True;";
                connect = new SqlConnection(con);
                connect.Open();
                //-----------------------------------------------------------------------------------------

                //Excute SQL----------------
                SqlCommand command;
          command = new SqlCommand("use master", connect);
            command.ExecuteNonQuery();
                command = new SqlCommand(@"restore database dbWiseCodes01 from disk = 'c:\SQLBackup\wcBackUp1.bak'", connect);
                command.ExecuteNonQuery();
                //--------------------------------------------------------------------------------------------------------
                connect.Close();

                MessageBox.Show("Has been restored database", "Restoration", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }
        else
            MessageBox.Show(@"Do not make any endorsement above (or is not in the correct path)", "Restoration", MessageBoxButtons.OK, MessageBoxIcon.Information);

    }
    catch (Exception exp)
    {
        MessageBox.Show(exp.Message);
    }

}

SQL: New versions of SQL Server 2008 Express

Wednesday, May 13th, 2009

Microsoft has released three versions of SQL Server 2008 Express Edition, these are:
* Microsoft SQL Server 2008 Express, this is the basic version of SQL Server 2008 Express Edition, this version with other applications redistribution is free.

* Microsoft SQL Server 2008 Express Tools with this version gives us work with applications that work with data, whether to narrow or web development, this version is ideal for small server storage applications and data storage, among the features best we can name:

* Admin Tools reliable and effective.
* Interesting data protection system.

* Microsoft SQL Server Express 2008 with Advanced Services includes more features and makes it easier than ever to develop effective data-driven applications for the web or local desktop. Other features include:

* A graphical management tool.
* Interesting features to create reports.
* Run reports from SQL Server Reporting Services on local relational data.

Link: Microsoft SQL Server 2008 Express,
Link: Microsoft SQL Server 2008 Express Tools
Link: Microsoft SQL Server Express 2008 with Advanced Services

Images in Access or SQL database

Saturday, May 9th, 2009

Description: An example of how to image files in an Access or SQL database and later display in VB

There are two possibilities:

* Save the path (without the image data itself)
* Save the complete image

The first solution is probably the simpler solution, because only the pure path of the image file is stored. Second option is a bit expensive, but has the advantage that the image will be displayed again if the image file itself is not (more) on the computer is available. The big disadvantage here is that the database, depending on the number of stored images (and image size) may become very large.

Save the image information in a memo
To view the entire image in a database, it is best to use a database field of type memo. Such content can have a field up to 1.2 GByte of memory. This should then also for larger image files are sufficient.

To do this, use the following routine:

'Image in variable (string) read
Public Function wcReadPicture(strFilename As String) As String

 Dim intF As Integer
 Dim strInhalt As String

 intF = FreeFile
 Open strFilename For Binary As #intF
 strInhalt = Space$(Lof(intF))
 Get #intF, , strInhalt
 Close #intF

 wcReadPicture = strInhalt

End Function

Whenever you’re a picture in the database must therefore call on the above function:

'Save Image in Database
Table.Edit
Table("wcImage") = wcReadPicture(Your_Image_Path)
Table.Update

Image database and read in Picture / Image View Object
Now the image from the database later in a PictureBox or an Image object again, create a temporary file and save to the contents of the database image field. About LoadPicture statement, the image can then be displayed. Then the temporary file is deleted again.

And here the code:

'Load image from database and display
Public Sub wcShowPicture(Picture As Control, ByVal strInhalt As String) 

 Dim intF As Integer

 'Create a temporary image file
 intF = FreeFile
 Open App.Path & "\wcImage.tmp" For Output As #intF
 Print #intF, strInhalt;
 Close #intF

 'Picture
 Picture.Picture = LoadPicture(App.Path & "\wcImage.tmp")

 'Delete temporary file
 Kill App.Path & "\wcImage.tmp"

End Sub

The call of the procedure is then as follows:

wcShowPicture Picture1, Table("wcImage")

Happy Programming!! ;-)

An Introduction to SQLite

Friday, May 8th, 2009

http://www.wisecodes.com/2009/05/an-introduction-to-sqlite/

SQLite is a small library written in C, which offers an engine for database SQL and implementing much of the standard SQL92 and ACID properties. In contrast to database servers like MySQL or PostgreSQL, its particularity is not to reproduce the usual client / server but to be integrated directly to programs using database files. SQLite is a public domain project created by D. Richard Hipp .

SQLite is the database engine as distributed through its offices in many large public software Skype, Firefox, Gears, and some products McAfee, in many languages like PHP, Python and Perl and some mobile phones whose iPhone and those running Symbian, which totals more than 200 million settlement of the library.

Features:

SQLite does not work on the paradigm client / server, but is a function library. Among its other features, it should be noted:

  • the absence of a procedure for installation and configuration. This includes the lack of account management and user rights.
  • whole database is stored in one file.
  • the type of data stored in each database is a property of the data, not the column. A column can contain data of different types.

SQLite implements most of the SQL 92 standard with the exception of:

  • management rights with GRANT and REVOKE
  • management of foreign keys
  • the joints type RIGHT OUTER JOIN and FULL OUTER JOIN (but supports LEFT OUTER JOIN)
  • the triggers are only partially taken into account
  • the possibilities of modifying the structure of a table are limited: you can rename a table and add columns, but not modify or delete columns.

SQLite can be interesting in performance and be useful in many cases (unable to use a database server for websites or applications and embedded devices, etc..), But it does not allow different processes or thread to access simultaneously write to the same database and is not designed to handle a lot of competitors.

The library can be used in Python, C and C + +. Modules for Perl, PHP, TCL and other scripting languages are available.

PHP includes SQLite in the distribution base since version 5, when it was released as version 4 in the form of an extension PECL.

Python SQLite 3 also includes in its standard library since version 2.5.

Link: Offical Website of SQLite
Link: Interview with Richard Hipp
Link: SQLiteSpy (compatible with Unicode for Win32. Freeware.)
Link: SQLite Database Browser
Link: SQLite Database Manager

Video: (An Introduction to SQLite)

SQL: Get First and Last Day of Week

Monday, May 4th, 2009

Description:
How to get First and Last Day of Week.

Select GETDATE() AS 'Today', 

DATEPART(Week,GETDATE()) AS 'Week No of Today', 

DATEADD( DAY , -DATEPART(WEEKDAY,(DATEADD( DAY , 7-DATEPART(WEEKDAY,GETDATE()),GETDATE())))
+(7-DATEPART(WEEKDAY,GETDATE()))+1 ,GETDATE()) 'First Day Of This Week', 

DATEADD(DAY , 7-DATEPART(WEEKDAY,GETDATE()),GETDATE()) AS 'Last Day Of Week'

Happy Programming!!

SQL: Get column names of a specified table.

Monday, May 4th, 2009

Description:
How to get column names of a specified table then do this code .

SELECT COLUMN_NAME As 'Columns' , DATA_TYPE As 'Type' FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'Your_Table_Name' ORDER BY ORDINAL_POSITION

OR

SELECT [NAME] AS 'Columns' FROM SYSCOLUMNS WHERE [ID] = Object_Id('Your_Table_Name')

Read More about INFORMATION_SCHEMA.COLUMNS 
Read More about SYSCOLUMNS

Happy Programming!!

Linking remote servers in SQL Server

Monday, April 13th, 2009

To the point:

See the linked servers that have:

exec sp_linkedservers

Add a new remote server to your links:

EXEC sp_addlinkedserver
@ server = 'server'
@ srvproduct ='product_name'
@ provider = 'provider_name'
@ datasrc = 'data_source'

Add credentials to access a remote server:

EXEC sp_addlinkedsrvlogin 'RemoteServerName', 'false', NULL, 'username', 'password'

And Hale, to throw the linked server.

More info on MSDN, here and here.

Happy Programming!!

SQL Server 2005 Tools

Monday, April 6th, 2009

Inside SQL Server 2005 you can find the following tools:

Database Services: Includes the database engine and components of search. The database engine is the core of SQL Server. Replication increases the availability of data among various databases, allowing to scale the workload of each server. The search query language allows level within the data stored in a database.

Analysis Services: Provides functionality for OLAP and Data Mining aimed at Business Intelligence applications. Analysis Services allows you to add data from multiple sources, including relational databases and data work in several ways.

Data Integration Services: Delivery data transformation and integration solutions to extract and process data from multiple sources and directions to one or more destinations. This link allows data from multiple sources and load data in the Data Warehouse.

Notification Services: includes a notification engine and components for customers to create and send personalized messages each time an event occurs. The notifications can be sent to wireless devices like cell phones or PDA’s, or Mail Messenger accounts.

Reporting Services: includes Report Manager and Report Server to provide a complete platform for creating, managing and distributing reports. Report Server is built on standard IIS and technology. NET Framework, allowing lso combine benefits of SQL Server and IIS for hosting and processing reports.

Service Broker: Allows creation of queues and messaging as the core of the database. Queues can be used to stack work, consultations and other applications, and implemented as resources become available. Messaging allows applications that use databases to communicate with them.

Cheers!!!

Add/Remove NewLine in SQL Query

Friday, February 13th, 2009

Add NewLine in SQL Query:

 
  Code:
Declare @FristName Char(10)
Declare @LastName Char(10) 
 
Set @FristName = 'Venu'
Set @LastName = 'Thomas' 
 
Select (@FristName + CHAR(13) + CHAR(10)+ @LastName) As Name
   

OutPut:

Name  
———————- 
Venu      
Thomas    

(1 row(s) affected)
 

Remove NewLine in SQL Query:

Code:


Declare @FristName Char(5)
Declare @LastName Char(10) 
Declare @strName Char(15) 
 
Set @FristName = 'Venu'
Set @LastName = 'Thomas'  
 
Set @strName =@FristName + CHAR(13) + CHAR(10)+ @LastName 
 
Select Replace(Replace(@strName, CHAR(13), ''), CHAR(10), ',') As Name
   

OutPut:

Name
————
Venu ,Thomas
(1 row(s) affected)