my $dbh=DBI->connect("DBI:Oracle:host=$hostname;sid=$sid",$username,$passwd);
### deal with multi return value
my $sql=qq(select uid_der from wbphish_usr_der);
$sth->execute();
my $sth=$dbh->prepare($sql);
$sth->execute() or die;
my @uid;
while(my @row=$sth->fetchrow_array)
{ push @uid,$row[0];}
### deal with single return value
my $sql="SELECT max(DEMO) FROM phishing"
$sth->execute();
my $sth=$dbh->prepare($sql);
$sth->execute() or die;
my $id=$dbh->selectrow_array($sql);
其中host是数据库server的ip地址,sid为连接的数据库。
连接SQL Server:
my $dbh = DBI->connect("dbi:ODBC:driver={SQL Server};Server=127.0.0.1;Database=$dbs;UID=$uid;PWD=$pwd");
my $sth = $dbh->prepare($sql);
$sth->execute();
其中Server是server的ip地址,这里是local地址,Database为连接的数据库。
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
/*Create Connection*/
//connection-string(Local Server:127.0.0.1) & SQL-string define
string conString = "Server=(local); database=test; uid=sa; password=123456";
string sqlString = "select top 10 " + metricName + ",MetricTime from Metric where MetricTime > @metricTime order by MetricTime";
//create a connection
SqlConnection con = new SqlConnection(conString);
con.Open();
/*First way*/
//create a SQL command within connection, use SqlDataReader(light-level) to read retrieved data
SqlCommand cmd = new SqlCommand(sqlString, con);
SqlParameter[] sps = new SqlParameter[] { new SqlParameter("@metricTime", metricTime) }; //Use SqlParameter to avoid "SQL injection".
cmd.Parameters.AddRange(sps);
SqlDataReader sdr = cmd.ExecuteReader();
//Read data from DataReader
while (sdr.Read())
Console.WriteLine((double)sdr[metricName]);
con.Close();
cmd.Dispose();
/*Second way*/
//create a SQL command within connection, use SqlDataAdapter to read retrieved data
SqlDataAdapter sqlDad = new SqlDataAdapter(sqlString, sqlCon);
SqlParameter sqlPar = new SqlParameter("@metricTime", metricTime); //Use SqlParameter to avoid "SQL injection".
sqlDad.SelectCommand.Parameters.Add(sqlPar);
DataSet metricDS = new DataSet("MetricDS");
sqlDad.Fill(metricDS, "Metric");
//Read data from DataSet
foreach (DataRow row in dst.Tables["Monitor"].Rows)
Console.WriteLine(row["ID"] + "\t" + row["RecordTime"] + "\t" + row["VideoView"] + "\t" + row["Fluency"]);
sqlCon.Close();
}
}
}
其中连接字串中Server是数据库server的ip地址,database是指定连接的数据库。
代码首先建立连接,然后分别以SqlDataReader和SqlDataAdapter两种方式处理了数据,且利用了SqlParameter来避免SQL injection。