SPANISH - Beginners Guide To Accessing SQL Server Through C#
SPANISH - Beginners Guide To Accessing SQL Server Through C#
through C#
By Matt Newman | 22 Aug 2004
A beginners guide to accessing a SQL or MSDE Server with C#
/w EPDw UKMTAy
Introduction
In this article I plan to demonstrate how to insert and read data from a SQL Server or
MSDE database. This code should work on both SQL Server , I am using 2000, and
MSDE. I am using Visual Studio 2002, but this should work with Visual Studio 2003,
Web Matrix, and the command line SDK. This code should work with both C#
applications and C# web applications and webservices. This code does not compile on
the FreeBSD with Rotor [^].
Spanish Translate:
Introducción
En este artículo me propongo demostrar cómo insertar y leer datos de un servidor SQL Server o
base de datos MSDE. This code should work on both SQL Server , I am using 2000, and MSDE. Este
código debería funcionar en el servidor SQL, estoy usando 2000 y MSDE. I am using Visual Studio
2002, but this should work with Visual Studio 2003, Web Matrix, and the command line SDK. Estoy
utilizando Visual Studio 2002, pero esto debería funcionar con Visual Studio 2003, Web Matrix, y el
SDK de línea de comandos. This code should work with both C# applications and C# web
applications and webservices. Este código debería funcionar tanto con aplicaciones de C # y C # las
aplicaciones web y servicios web. This code does not compile on the FreeBSD with [ ]. Este código
no se compila en el FreeBSD con rotor [ ^ ].
Background
Part of my current project required me too store and retrieve information from a
database. I decided to use C# as my target language since I am currently reading
Inside C# Second Edition [^] by Tom Archer [^], which by the way is a must have
book. However I could not find any examples that were clear and just generic accesing
SQL Server with C#.
Spanish Translate:
Antecedentes
Part of my current project required me too store and retrieve information from a
database. Parte de mi proyecto actual requiere yo también almacenar y recuperar
información de una base de datos. I decided to use C# as my target language since I
am currently reading [ ] by [ ], which by the way is a must have book. Decidí usar C
# como mi idioma de destino ya que estoy leyendo actualmente dentro de C #
Segunda edición [ ^ ] por Tom Archer [ ^ ], que por cierto es una necesidad tiene
libro. However I could not find any examples that were clear and just generic accesing
SQL Server with C#. Sin embargo no pude encontrar ningún ejemplo de que fueron
claras y justas accediendo genéricos de SQL Server con C #.
I did not include a sample application because the code provide within the article can
really be dropped in and should work with no problem. Also through out the article I
will refer to SQL Server, MSDE is a free version of SQL Server that does not have some
of the GUI tools and has a few other limits such as database size. This code will work
on both without problem.
Usando el código
I did not include a sample application because the code provide within the article can
really be dropped in and should work with no problem. No incluí una aplicación de
ejemplo porque el código proporcionar, en el artículo realmente se puede quitar y
debería funcionar sin problema. Also through out the article I will refer to SQL Server,
MSDE is a free version of SQL Server that does not have some of the GUI tools and
has a few other limits such as database size. También a través de los artículo me
referiré a SQL Server, MSDE es una versión gratuita de SQL Server que no tiene
algunas de las herramientas de la GUI y tiene unos límites tales como el tamaño de
base de datos. This code will work on both without problem. Este código funciona en
ambos sin problema.
using System.Data.SqlClient;
SqlConnection.ConnectionString
The connection string is simply a compilation of options and values to specify how and
what to connect to. Upon investigating the Visual Studio .NET help files I discovered
that several fields had multiple names that worked the same, like Password and Pwd
work interchangeably. I have not included all of the options for
SqlConnection.ConnectionString at this time. As I get a chance to test and use
these other options I will include them in the article.
La cadena de conexión es simplemente una recopilación de las opciones y los valores para
especificar cómo y por qué conectar. Upon investigating the Visual Studio .NET help files I
discovered that several fields had multiple names that worked the same, like and work
interchangeably. Al investigar el Visual Studio. NET archivos de ayuda, descubrí que había varios
campos de varios nombres que trabajó el mismo, como Password y Pwd trabajo
indistintamente. I have not included all of the options for at this time. No he incluido todas las
opciones para SqlConnection.ConnectionString en este momento. As I get a chance to
test and use these other options I will include them in the article. Como tengo la oportunidad de
probar y utilizar otras opciones que se les incluya en el artículo.
User ID
The User ID is used when you are using SQL Authentication. In my experience this is
ignored when using a Trusted_Connection, or Windows Authentication. If the username
is associated with a password Password or Pwd will be used.
"user id=userid;"
Password or Pwd
The password field is to be used with the User ID, it just wouldn't make sense to log in
without a username, just a password. Both Password and Pwd are completely
interchangeable.
"Password=validpassword;"-or-
"Pwd=validpassword;"
Upon looking in the MSDN documentation I found that there are several ways to
specify the network address. The documentation mentions no differences between
them and they appear to be interchangeable. The address is an valid network address,
for brevity I am only using the localhost address in the examples.
"Data Source=localhost;"
-or-
"Server=localhost;"
-or-
"Address=localhost;"-or-"Addr=localhost;"
-or-"Network Address=localhost;"
These specify the time, in seconds, to wait for the server to respond before generating
an error. The default value is 15 (seconds).
"Connect Timeout=10;"-or-
"Connection Timeout=10;"
"Inital Catalog=main;"
-or-
"Database=main;"
The Network Library option is essential if your are communicating with the server on a
protocl other than TCP/IP. The default value for Network Library is dbmssocn, or
TCP/IP. The following options are available: dbnmpntw (Named Pipes), dbmsrpcn
(Multiprotocol), dbmsadsn (Apple Talk), dbmsgnet (VIA), dbmsipcn (Shared
Memory), and dbmsspxn (IPX/SPX), and dbmssocn (TCP/IP). And as before
Network Library and Net can be user interchangably. Note: The corresponding
network protocol must be installed on the system to which you connect.
TRADUCCION ESPAÑOLA
ID de usuario
The is used when you are using SQL Authentication. El User ID se utiliza cuando se
está utilizando autenticación de SQL. In my experience this is ignored when using a
Trusted_Connection, or Windows Authentication. En mi experiencia, esto se ignora
cuando se utiliza un Trusted_Connection, o la autenticación de Windows. If the
username is associated with a password or will be used. Si el nombre de usuario está
asociado con una contraseña Password o Pwd se utilizará.
The password field is to be used with the User ID, it just wouldn't make sense to log in
without a username, just a password. El campo de la contraseña que se utiliza con el
ID de usuario, simplemente no tiene sentido hacer una sesión sin un nombre de
usuario, sólo una contraseña. Both and are completely interchangeable. Ambos
Password y Pwd son completamente intercambiables.
and are used to specify wheter the connnection is secure, such as Windows
Authentication or SSPI. Integrated Security y Trusted_Connection se utilizan
para especificar si la función CONEXIÓN es segura, como la autenticación de Windows
o SSPI. The recognized values are , , and . Los valores reconocidos son true ,
false , y sspi . According to the MSDN documentation is equivalent to . I do not
know how works, or affects the connection. De acuerdo con la documentación de
MSDN sspi es equivalente a la true . Tenga en cuenta que no sé cómo SSPI obras,
o afecta a la conexión.
These specify the time, in seconds, to wait for the server to respond before generating
an error. Estos especificar el tiempo, en segundos, esperar a que el servidor responda
antes de generar un error. The default value is (seconds). El valor por defecto es 15
(segundos).
and are simply two ways of selecting the database associated with the connection.
Initial Catalog y Database son simplemente dos maneras de seleccionar la base
de datos asociados a la conexión.
" Inital Catalog=main;"
-O-
" Database=main;"
The Network Library option is essential if your are communicating with the server on a
protocl other than TCP/IP. La opción de biblioteca de red es esencial para que el se
está comunicando con el servidor en un protocolo de comunicacion otras de TCP / IP.
The default value for is , or TCP/IP. El valor por defecto para Network Library es
dbmssocn , o TCP / IP. The following options are available: (Named Pipes),
(Multiprotocol), (Apple Talk), (VIA), (Shared Memory), and (IPX/SPX), and
(TCP/IP). Las opciones disponibles son las siguientes: dbnmpntw (canalizaciones),
dbmsrpcn (multiprotocolo), dbmsadsn (Apple Talk), dbmsgnet (VIA), dbmsipcn
(memoria compartida), y dbmsspxn (IPX / SPX), y dbmssocn (TCP / IP). And as
before and can be user interchangably. The corresponding network protocol be
installed on the system to which you connect. Y como antes Network Library y Net
puede ser indistintamente de usuario:. Nota: el protocolo de red correspondiente
debe estar instalado en el sistema al que se conecta.
SqlConnection.Open()
This is the last part of getting connected and is simply executed by the following
(remember to make sure your connection has a connection string first):
Esta es la última parte de conectarse y es simplemente ejecutados por el texto siguiente (recuerde
asegurarse de que su conexión tiene una cadena de conexión primero):
try
{
myConnection.Open();
}
catch(Exception e)
{
Console.WriteLine(e.ToString());
}
SqlConnection.Open() is a void function and does not return an error but throws
an exception so remember to put it in a try/catch brace. rather than having the
program explode in front of the user.
SqlConnection.Open() es una función void y no devuelve un error, pero se produce una
excepción a fin de recordar a ponerlo en un try / catch corsé. rather than having the program
explode in front of the user. en lugar de tener el programa de explotar en frente del usuario.
Command thee
SQL commands are probably the most difficult part of using an SQL database, but
the .NET framework has wrapped up everything up nicely and takes most of the guess
work out.
Te mando
SQL commands are probably the most difficult part of using an SQL database, but
the .NET framework has wrapped up everything up nicely and takes most of the guess
work out. comandos SQL son probablemente la parte más difícil de usar una base de
datos SQL, pero el marco. NET ha envuelto todo muy bien y tiene la mayor parte de
las conjeturas.
SqlCommand
Any guesses on what SqlCommand is used for? If you guessed for SQL commands then
you are right on. An SqlCommand needs at least two things to operate. A command
string, and a connection. First we'll look at the connection requirement. There are two
ways to specify the connection, both are illustrated below:
Comando Sql
// - or -
myCommand.Connection = myConnection;
The connection string can also be specified both ways using the
SqlCommand.CommandText property. Now lets look at our first SqlCommand. To keep
it simple it will be a simple INSERT command.
// - or -
Now we will take a look at the values . table is simply the table within the database.
Column1 and Column2 are merely the names of the columns. Within the values
section I demonstrated how to insert a string type and an int type value. The string
value is placed in single quotes and as you can see an integer is just passed as is. The
final step is to execute the command with:
Ahora vamos a echar un vistazo a los valores. table no es más que la tabla en la base de datos.
Column1 y Column2 no son más que los nombres de las columnas. Within the values section I
demonstrated how to insert a type and an type value. Dentro de la sección de valores que
demostró cómo insertar una string tipo y un int valor de tipo. The string value is placed in
single quotes and as you can see an integer is just passed as is. El valor de cadena se coloca entre
comillas simples y como se puede ver un número entero se acaba de aprobar como está. The final
step is to execute the command with: El último paso es ejecutar el comando con:
myCommand.ExecuteNonQuery();
SqlDataReader
Inserting data is good, but getting the data out is just as important. Thats when the
SqlDataReader comes to the rescue. Not only do you need a data reader but you
need a SqlCommand. The following code demonstrates how to set up and execute a
simple reader:
Inserting data is good, but getting the data out is just as important.Inserción de los
datos es bueno, pero conseguir los datos fuera es tan importante. Thats when the
comes to the rescue. Eso es cuando el SqlDataReader viene al rescate. Not only do
you need a data reader but you need a . No sólo se necesita un lector de datos, pero
se necesita un SqlCommand . The following code demonstrates how to set up and
execute a simple reader: El código siguiente muestra cómo configurar y ejecutar un
simple lector:
try
{
SqlDataReader myReader = null;
SqlCommand myCommand = new SqlCommand("select * from table",
myConnection);
myReader = myCommand.ExecuteReader();
while(myReader.Read())
{
Console.WriteLine(myReader["Column1"].ToString());
Console.WriteLine(myReader["Column2"].ToString());
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
As you can see the SqlDataReader does not access the database, it merely holds the
data and provides an easy interface to use the data. The SqlCommand is fairly simple,
table is the table your are going to read from. Column1 and Column2 are just the
columns as in the table. Since there is a very high probability your will be reading
more than one line a while loop is required to retrieve all of the records. And like
always you want to try it and catch it so you don't break it.
SqlParameter
Parametro Sql
Its all fine and dandy if the user puts in correct syntax, however, what happens if the
user puts value1, DROP table. Best case scenario it will cause an exception (I
haven't checked to see what this example will do but it demonstrates a point), worst
case you can kiss your table goodbye. You could parse all user input and strip out
anything that could cause problems OR you could use an SqlParameter. Now the
SqlParameter class is pretty big, but I will just show you a basic parameter usage.
Basically you need three things to create a parameter. A name, data type, and size.
(note for some data types you will want to leave off the size, such as Text).
Es todo bien y dandy si el usuario pone en la sintaxis correcta, sin embargo, ¿qué pasa si el usuario
pone value1, DROP table . Best case scenario it will cause an exception (I haven't checked
to see what this example will do but it demonstrates a point), worst case you can kiss your table
goodbye. Mejor de los casos se hará una excepción (no lo he comprobado al ver lo que este
ejemplo va a hacer, pero muestra un punto), en el peor caso, puede despedirte de tu mesa. You
could parse all user input and strip out anything that could cause problems OR you could use an .
Usted podría analizar todas las entradas del usuario y la tira a cabo cualquier cosa que pueda
causar problemas O usted podría utilizar un SqlParameter . Now the class is pretty big, but I
will just show you a basic parameter usage. Ahora el SqlParameter clase es bastante grande,
pero yo sólo le mostrará el uso de un parámetro básico. Basically you need three things to create a
parameter. Básicamente se necesitan tres cosas para crear un parámetro. A name, data type, and
size. Un nombre, tipo de datos y el tamaño. (note for some data types you will want to leave off
the size, such as ). (Nota para algunos tipos de datos que va a querer dejar el tamaño, tales como
Text ).
It is naming convention, it might be required I'm not sure, to name all parameters
starting with the @ symbol. Now how do you use a parameter? Will its pretty easy as
the following code shows.
Es convención de nombres, puede ser necesario no estoy seguro, a nombre de todos los
parámetros a partir de la @ símbolo. Now how do you use a parameter? Ahora, ¿cómo usar un
parámetro? Will its pretty easy as the following code shows. Se es bastante fácil como muestra el
siguiente código.
Now this keeps a rogue user from high-jacking your command string. This isn't all
there is to parameters if you want to learn more advanced topics a good place to start
is here[^].
Ahora bien, este mantiene un usuario malicioso de alta elevación de su cadena de comando. This
isn't all there is to parameters if you want to learn more advanced topics a good place to start is [
]. Esto no es todo lo que hay parámetros si quieres aprender temas avanzados de más un buen
lugar para comenzar es aquí [ ^ ].
Don't forget to close up when your done!
try
{
myConnection.Close();
}
catch(Exception e)
{
Console.WriteLine(e.ToString());
}
The trusted connection had always been a mystery to me, I had never figured why IIS
and SQL server never seemed to get along. Fortunately Pete (moredip) pointed out a
helpful section of the documentation. To make it more simple I have decided to add it
to this article. I am going to split this into 2 different sections. IIS 6, and other
versions of IIS. To get started your going to want to make sure osql.exe is in your
system path, or find it. It should be located wherever your SQL Server 2000
server/client tools directory. On my system it is something like this: %Install
Directory%\80\Tools\BINN\.For simplicity I will use psuedo-variables in the
examples so as not to create confusion. For example a psuedo-variable will look like
this: %VARIABLE%. The server will be referred to as %SERVER%\%INSTANCE%. If you
aren't using any instance names it can be just %SERVER%, (local) if the server is the
local machine. If you are instance names it would be something like
ServerName\ServerInstance etc etc. I will also be using %DATABASE% to refer to
the database name.
I know this will work on IIS 6 with Windows 2003 Server because I have done it and
that is currently the only OS with IIS 6. On IIS 6 the ASP.NET process runs under the
account 'NT AUTHORITY\NETWORK SERVICE'.
These 2 lines will add access to one of the databases. So if you want to add access to
another database just change %DATABASE% and run both lines.
IIS 5.1
This should work on all other IIS 5.1 (possibly other versions) combinations. The only
difference between IIS 5.1 and IIS 6 is the account the ASP.NET process runs under.
IIS 5.1 runs under a %MACHINENAME%\ASPNET where %MACHINENAME% is the machine
name.
Now our ASP.NET application will be able to log into the server. Now all thats left is to
grant access to the databases.
These 2 lines will add access to one of the databases. So if you want to add access to
another database just change %DATABASE% and run both lines.
Loose Ends