อยากทราบวิธีการเขียน vb connect sql server2005 โดยเปนแบบโมดูลที่เรียกใช้ได้เลย
เขียนเป็น class สิครับ .net นี่ base on oop อยู่แล้ว ถ้าเป็นเป็นรับรองลืม php ไปเลย
Date :
2010-06-07 08:35:45
By :
tungman
Code (VB.NET)
Imports System.Data
Imports System.Data.SqlClient
Imports System.Configuration
Public Class clsDatabase
Private objConn As SqlConnection
Private objCmd As SqlCommand
Private Trans As SqlTransaction
Private strConnString As String
Public Sub New()
strConnString = System.Configuration.ConfigurationSettings.AppSettings("ConnectionString")
End Sub
Public Function QueryDataReader(ByVal strSQL As String) As SqlDataReader
Dim dtReader As SqlDataReader
objConn = New SqlConnection
With objConn
.ConnectionString = strConnString
.Open()
End With
objCmd = New SqlCommand(strSQL, objConn)
dtReader = objCmd.ExecuteReader()
Return dtReader '*** Return DataReader ***'
End Function
Public Function QueryDataSet(ByVal strSQL As String) As DataSet
Dim ds As New DataSet
Dim dtAdapter As New SqlDataAdapter
objConn = New SqlConnection
With objConn
.ConnectionString = strConnString
.Open()
End With
objCmd = New SqlCommand
With objCmd
.Connection = objConn
.CommandText = strSQL
.CommandType = CommandType.Text
End With
dtAdapter.SelectCommand = objCmd
dtAdapter.Fill(ds)
Return ds '*** Return DataSet ***'
End Function
Public Function QueryDataTable(ByVal strSQL As String) As DataTable
Dim dtAdapter As SqlDataAdapter
Dim dt As New DataTable
objConn = New SqlConnection
With objConn
.ConnectionString = strConnString
.Open()
End With
dtAdapter = New SqlDataAdapter(strSQL, objConn)
dtAdapter.Fill(dt)
Return dt '*** Return DataTable ***'
End Function
Public Function QueryExecuteNonQuery(ByVal strSQL As String) As Boolean
objConn = New SqlConnection
With objConn
.ConnectionString = strConnString
.Open()
End With
Try
objCmd = New SqlCommand
With objCmd
.Connection = objConn
.CommandType = CommandType.Text
.CommandText = strSQL
End With
objCmd.ExecuteNonQuery()
Return True '*** Return True ***'
Catch ex As Exception
Return False '*** Return False ***'
End Try
End Function
Public Function QueryExecuteScalar(ByVal strSQL As String) As Object
Dim obj As Object
objConn = New SqlConnection
With objConn
.ConnectionString = strConnString
.Open()
End With
Try
objCmd = New SqlCommand
With objCmd
.Connection = objConn
.CommandType = CommandType.Text
.CommandText = strSQL
End With
obj = objCmd.ExecuteScalar() '*** Return Scalar ***'
Return obj
Catch ex As Exception
Return Nothing '*** Return Nothing ***'
End Try
End Function
Public Function TransStart()
objConn = New SqlConnection
With objConn
.ConnectionString = strConnString
.Open()
End With
Trans = objConn.BeginTransaction(IsolationLevel.ReadCommitted)
End Function
Public Function TransExecute(ByVal strSQL As String) As Boolean
objCmd = New SqlCommand
With objCmd
.Connection = objConn
.Transaction = Trans
.CommandType = CommandType.Text
.CommandText = strSQL
End With
objCmd.ExecuteNonQuery()
End Function
Public Function TransRollBack()
Trans.Rollback()
End Function
Public Function TransCommit()
Trans.Commit()
End Function
Public Sub Close()
objConn.Close()
objConn = Nothing
End Sub
End Class
ตัวอย่างครับ
Date :
2010-06-07 08:43:34
By :
webmaster
Date :
2010-06-07 08:45:45
By :
webmaster
ขอร่วมด้วยนะครับ
Code (VB.NET)
imports system.data
imports system.data.sqlclient
module connectionsql
private con as new sqlconnection
private stringConneciton as string =""
private sub connectionstringsql(byvel icase as interger) 'เลือก connect database
select case icase
case 1
stringConnection = "Data Source=server1;Initial Catalog=DB1;User ID=sa;Password=password;"
case 2
stringConnection ="Data Source=server2;Initial Catalog=DB2;User ID=sa;Password=password"
case 3
stringConnection =""
end select
end sub
private sub InitailSql()
if con.state = connectionstate.open then con.close()
con.connectionstring = stringConnection
con.open()
end sub
end module
public sub ConnectDBSql(byvel iDB as interger)
connectionstringsql(iDB)
InitailSql()
end sub
ขั้นตอนการใช้งาน
Code (VB.NET)
private sub btnSubmit_click...
dim sb as new stringbuilder
ConnectDBSql(1) ' สมมุติว่า ต่อ DB1
sb.remove(0,sb.length)
sb.append("select * from mytable")
.
.
.
end sub
end
ผิดพลาดประการใด ขอ อภัยด้วยครับ
Date :
2010-06-07 11:55:26
By :
tee
ว้าอดเลย มีแต่แบบ c# web
SqlDatabaseManager.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Data.SqlClient;
using System.Globalization;
using System.IO;
using System.Text.RegularExpressions;
using System.Web.Configuration;
#region ========== Class SqlDatabaseManager ==========
/// <summary>
/// Summary description for SqlDatabase
/// </summary>
public class SqlDatabaseManager
{
#region ========== Field ==========
private SqlConnection sqlConnection;
private SqlCommand sqlCommand;
private SqlTransaction sqlTransaction;
private List<string> errorCommand;
private string sqlConnectionString = string.Empty;
private string sqlConnectionKeyName = string.Empty;
private string sqlCommandString = string.Empty;
private string commandMessage = "You must execute command.";
private bool commandSuccess = false;
private bool transaction = false;
private int rowsAffected = 0;
#endregion
#region ========= Constructor ==========
/// <summary>
/// Use sql connection string from web.config configulation.
/// </summary>
public SqlDatabaseManager()
{
if (WebConfigurationManager.ConnectionStrings["SqlConnectionString"] != null)
{
//สำหรับ web.config ที่มีการ add connection string ชื่อ SqlConnectionString เอาไว้
//
//ตัวอย่างใน web.config
//<connectionStrings>
// <add name="SqlConnectionString" connectionString="Data Source=.\SQLEXPRESS;Initial Catalog=SqlDatabase;Integrated Security=True;" providerName="System.Data.SqlClient"/>
//</connectionStrings>
sqlConnectionKeyName = "SqlConnectionString";
sqlConnectionString = WebConfigurationManager.ConnectionStrings["SqlConnectionString"].ToString();
sqlConnection = new SqlConnection(sqlConnectionString);
}
else
{
sqlConnection = new SqlConnection();
}
}
/// <summary>
/// Use sql connection string from web.config configulation by key name.
/// </summary>
public SqlDatabaseManager(string SqlConnectionKeyName)
{
sqlConnectionKeyName = SqlConnectionKeyName;
sqlConnectionString = WebConfigurationManager.ConnectionStrings[sqlConnectionKeyName].ToString();
sqlConnection = new SqlConnection(sqlConnectionString);
}
/// <summary>
/// Use sql connection string by user define.
/// </summary>
public SqlDatabaseManager(string SqlConnectionKeyName, string SqlConnectionString)
{
sqlConnectionKeyName = SqlConnectionKeyName;
sqlConnectionString = SqlConnectionString;
sqlConnection = new SqlConnection(sqlConnectionString);
}
#endregion
#region ========== Property ==========
/// <summary>
/// Gets or sets Sql connection key name from web.config.
/// </summary>
public virtual string ConnectionKeyName
{
get { return sqlConnectionKeyName; }
set
{
sqlConnectionKeyName = value;
sqlConnectionString = WebConfigurationManager.ConnectionStrings[sqlConnectionKeyName].ToString();
sqlConnection = new SqlConnection(sqlConnectionString);
}
}
/// <summary>
/// Gets or sets Sql connection.
/// </summary>
public virtual string ConnectionString
{
get { return sqlConnectionString; }
set
{
sqlConnectionString = value;
sqlConnection = new SqlConnection(sqlConnectionString);
}
}
/// <summary>
/// Gets or sets Sql command.
/// </summary>
public virtual string CommandString
{
get { return sqlCommandString; }
set
{
sqlCommandString = ConvertDateCommand(value);
sqlCommand = new SqlCommand(sqlCommandString, sqlConnection);
commandMessage = "You must execute command.";
commandSuccess = false;
rowsAffected = 0;
if (transaction)
sqlCommand.Transaction = sqlTransaction;
}
}
/// <summary>
/// Check for Sql command.
/// </summary>
public virtual bool IsSuccess
{
get { return commandSuccess; }
}
/// <summary>
/// Gets message from Sql command.
/// </summary>
public virtual string Message
{
get { return commandMessage; }
}
/// <summary>
/// Gets Number of rows affected.
/// </summary>
public virtual int RowsAffected
{
get { return rowsAffected; }
}
#endregion
#region ========== Method ==========
/// <summary>
/// Add the parameter value to the sql command.
/// </summary>
/// <param name="ParameterName">The name of Parameter.</param>
/// <param name="ParameterValue">The value to be added.</param>
public virtual void AddParameter(string ParameterName, object ParameterValue)
{
sqlCommand.Parameters.AddWithValue(ParameterName, ParameterValue);
}
/// <summary>
/// Start Sql Transaction.
/// </summary>
public virtual void TransactionStart()
{
transaction = true;
errorCommand = new List<string>();
if (sqlConnection.State != ConnectionState.Open)
sqlConnection.Open();
sqlTransaction = sqlConnection.BeginTransaction(IsolationLevel.ReadCommitted);
}
/// <summary>
/// Execute Sql Transaction.
/// </summary>
/// <returns>Result of transaction.</returns>
public virtual bool ExecuteTransaction()
{
transaction = false;
if (errorCommand.Count == 0)
{
sqlTransaction.Commit();
commandMessage = "All command is successfully. <font color=\"darkgreen\">Transaction Commited.</font>";
commandSuccess = true;
}
else
{
sqlTransaction.Rollback();
string ErrorText = "Some command has error. <font color=\"red\">Transaction Rollback.</font><br />Error in: <br />";
foreach (string aErrorSqlCommand in errorCommand)
{
ErrorText += aErrorSqlCommand + "<br />";
}
commandMessage = ErrorText;
commandSuccess = false;
}
errorCommand.Clear();
if (sqlConnection.State == ConnectionState.Open)
sqlConnection.Close();
sqlTransaction.Dispose();
sqlCommand.Dispose();
sqlConnection.Dispose();
return commandSuccess;
}
/// <summary>
/// Execute Query Sql command.
/// </summary>
/// <returns>Query data in DataTable.</returns>
public virtual DataTable ExecuteQuery()
{
DataTable dataTable = new DataTable();
try
{
SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(sqlCommand);
sqlDataAdapter.Fill(dataTable);
sqlDataAdapter.Dispose();
if (!transaction)
{
sqlCommand.Dispose();
sqlConnection.Dispose();
}
commandMessage = "Command is successfully.";
commandSuccess = true;
}
catch (Exception ex)
{
commandMessage = ErrorMessage(ex.Message);
commandSuccess = false;
}
rowsAffected = dataTable.Rows.Count;
return dataTable;
}
/// <summary>
/// Execute Scalar Sql command.
/// </summary>
/// <returns>Object of value.</returns>
public virtual object ExecuteScalar()
{
object Result = 0;
try
{
if (transaction)
{
Result = sqlCommand.ExecuteScalar();
}
else
{
if (sqlConnection.State != ConnectionState.Open)
sqlConnection.Open();
Result = sqlCommand.ExecuteScalar();
sqlConnection.Close();
sqlCommand.Dispose();
sqlConnection.Dispose();
}
commandMessage = "Command is successfully.";
commandSuccess = true;
}
catch (Exception ex)
{
commandMessage = ErrorMessage(ex.Message);
commandSuccess = false;
AddErrorCommand(sqlCommandString, ex.Message);
}
return Result;
}
/// <summary>
/// Execute Non Query Sql command.
/// </summary>
/// <returns>Result of execute command.</returns>
public virtual bool ExecuteNonQuery()
{
rowsAffected = 0;
try
{
if (transaction)
{
rowsAffected = sqlCommand.ExecuteNonQuery();
}
else
{
if (sqlConnection.State != ConnectionState.Open)
sqlConnection.Open();
rowsAffected = sqlCommand.ExecuteNonQuery();
sqlConnection.Close();
sqlCommand.Dispose();
sqlConnection.Dispose();
}
commandMessage = "Command is successfully.";
commandSuccess = true;
}
catch (Exception ex)
{
commandMessage = ErrorMessage(ex.Message);
commandSuccess = false;
AddErrorCommand(sqlCommandString, ex.Message);
}
return commandSuccess;
}
/// <summary>
/// Build error message.
/// </summary>
/// <param name="Message">Message string.</param>
/// <returns>Error message string.</returns>
protected virtual string ErrorMessage(string MessageString)
{
return "<font color=\"red\">Command error.</font> " + MessageString;
}
/// <summary>
/// Add error sql command to string collections.
/// </summary>
/// <param name="commandString">The sql command.</param>
/// <param name="errorMessage">The error message.</param>
protected virtual void AddErrorCommand(string commandString, string errorMessage)
{
errorCommand.Add(commandString + " <font color=\"red\">[Error message: " + errorMessage + "]</font>");
}
/// <summary>
/// Convert native command to sql command.
/// </summary>
/// <param name="commandString">The native sql command.</param>
/// <returns>The standard sql command.</returns>
protected virtual string ConvertDateCommand(string commandString)
{
string SmallDateTimePattern = "[sS][mM][aA][lL][lL][dD][aA][tT][eE][tT][iI][mM][eE]\\([@][0-9a-zA-Z\\s]{1,}\\)";
Regex SmallDateTimeRgx = new Regex(SmallDateTimePattern);
foreach (Match SmallDateTimeMatchCase in SmallDateTimeRgx.Matches(commandString))
{
string MatchCasePattern = "^[sS][mM][aA][lL][lL][dD][aA][tT][eE][tT][iI][mM][eE]";
Regex MatchCaseRgx = new Regex(MatchCasePattern);
Match RemoveMatch = MatchCaseRgx.Match(SmallDateTimeMatchCase.Value);
string TempMatchCase = SmallDateTimeMatchCase.Value.Replace(RemoveMatch.Value, "");
commandString = commandString.Replace(SmallDateTimeMatchCase.Value, TempMatchCase.Replace("(", "Convert(SmallDateTime, ").Replace(")", ", 103)"));
}
string DateTimePattern = "[dD][aA][tT][eE][tT][iI][mM][eE]\\([@][0-9a-zA-Z\\s]{1,}\\)";
Regex DateTimeRgx = new Regex(DateTimePattern);
foreach (Match DateTimeMatchCase in DateTimeRgx.Matches(commandString))
{
string MatchCasePattern = "^[dD][aA][tT][eE][tT][iI][mM][eE]";
Regex MatchCaseRgx = new Regex(MatchCasePattern);
Match RemoveMatch = MatchCaseRgx.Match(DateTimeMatchCase.Value);
string TempMatchCase = DateTimeMatchCase.Value.Replace(RemoveMatch.Value, "");
commandString = commandString.Replace(DateTimeMatchCase.Value, TempMatchCase.Replace("(", "Convert(DateTime, ").Replace(")", ", 103)"));
}
return commandString;
}
#endregion
}
#endregion
#region ========== Class SqlConvert ==========
/// <summary>
/// Summary description for SqlConvert
/// </summary>
public sealed class SqlConvert
{
/// <summary>
/// Convert to byte[].
/// </summary>
/// <param name="BinaryStream">File upload binary stream.</param>
/// <param name="StreamLength">Lenght of File upload binary stream.</param>
/// <returns>Byte[] of binary stream.</returns>
public static byte[] ToVarBinary(Stream BinaryStream, int StreamLength)
{
BinaryReader BinaryRead = new BinaryReader(BinaryStream);
byte[] binaryData = BinaryRead.ReadBytes(StreamLength);
return binaryData;
}
/// <summary>
/// Convert to DataTime DataType with d/M/yyyy format.
/// </summary>
/// <param name="DateString">DateTime sring.</param>
/// <returns>Datetime Type.</returns>
public static DateTime ToDateTime(string DateString)
{
//ควรกำหนด culture ใน web.config เป็น th
//
//ตัวอย่างใน web.config
//<globalization requestEncoding="utf-8" responseEncoding="utf-8" culture="th-TH" uiCulture="th-TH"/>
return DateTime.ParseExact(DateString, "d/M/yyyy", CultureInfo.InvariantCulture);
}
/// <summary>
/// Convert to DataTime DataType with user define format.
/// </summary>
/// <param name="DateString">DateTime sring.</param>
/// <param name="DateFormat">DateTime Format</param>
/// <returns>Datetime Type.</returns>
public static DateTime ToDateTime(string DateString, string DateFormat)
{
//ควรกำหนด culture ใน web.config เป็น th
//
//ตัวอย่างใน web.config
//<globalization requestEncoding="utf-8" responseEncoding="utf-8" culture="th-TH" uiCulture="th-TH"/>
return DateTime.ParseExact(DateString, DateFormat, CultureInfo.InvariantCulture);
}
}
#endregion
Date :
2010-06-07 12:06:24
By :
tungman
Load balance : Server 05