TECHNOLOGIES
FORUMS
JOBS
BOOKS
EVENTS
INTERVIEWS
Live
MORE
LEARN
Training
CAREER
MEMBERS
VIDEOS
NEWS
BLOGS
Sign Up
Login
No unread comment.
View All Comments
No unread message.
View All Messages
No unread notification.
View All Notifications
Answers
Post
An Article
A Blog
A News
A Video
An EBook
An Interview Question
Ask Question
Forums
Monthly Leaders
Forum guidelines
Kevin Bullen
NA
1
0
noob cast object as sqlconnection
Aug 10 2009 4:04 PM
Converting from vb to c#, simple question, I hope.
In vb, I can declare a variable as an object
Private _oConn As Object
and then depending connection type needed:
Select Case Connection
Case Connections.SQLServer
_oConn = New SqlConnection()
Case Connections.ODBCConn
_oConn = New Odbc.OdbcConnection()
End Select
Anywhere in the code after that I can write a _oConn.Open, .Close, .ExecuteScalar, etc... and it compiles, no worries
When I try the same thing with C#, it won't even compile, complains :'object' does not contain a definition for 'Close' and no extension method 'Close' accepting a first argument of type 'object' could be found
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Data.Odbc;
using System.Data.SqlClient;
namespace CustomerMaintenance
{
public class DAL
{
private object _oConn = null;
public enum Connections
{
SQLServer = 1,
ODBCConn = 3,
};
public DAL(Connections Connection, string ODBCDriver, string UserID, string Password, string DataSource, string Database, int ConnectTimeout)
{
try
{
switch (Connection)
{
case Connections.SQLServer:
{
SqlConnection _oConn = new SqlConnection("user id=" + UserID + ";" +
"password=" + Password + ";" +
"data source=" + DataSource + ";" +
"initial catalog=" + Database + ";" +
"Connect Timeout = " + ConnectTimeout.ToString() + ";");
};
break;
case Connections.ODBCConn:
{
OdbcConnection _oConn = new OdbcConnection("Driver=" + ODBCDriver + ";" +
"System=" + DataSource + ";" +
"Uid=" + UserID + ";" +
"Pwd=" + Password + ";");
_oConn.ConnectionTimeout = ConnectTimeout;
};
break;
}
}
catch
{
}
finally
{
}
}
public int ExecuteScalar(string stringCommand, int intCommandTimeout, int intConnectionTimeout)
{
SqlConnection localConn = (SqlConnection)_oConn;
int intRetVal = 0;
SqlCommand sqlcmdCommand = new SqlCommand();
try
{
sqlcmdCommand.CommandType = CommandType.Text;
sqlcmdCommand.CommandText = stringCommand;
sqlcmdCommand.CommandTimeout = intCommandTimeout;
_oConn.Open();
<-- Will not compile
sqlcmdCommand.Connection = localConn;
intRetVal = Convert.ToInt16(sqlcmdCommand.ExecuteScalar());
return intRetVal;
}
catch
{
return 0;
}
finally
{
_oConn.Close();
<-- will not compile
sqlcmdCommand.Clone();
sqlcmdCommand.Dispose();
}
}
}
}
Reply
Answers (
1
)
Connecting SQL Server 2005 database from Windows Mobile 6.0
SearchQuery