原文:c#数据库操作大全

1.提取单条记录
//using System.Data;
//using System.Data.SqlClient;
 using (SqlConnection cn = new SqlConnection(%%1))
//ConfigurationManager.ConnectionStrings["db2ConnectionString"].ConnectionString
//Data Source=myServerAddress;Initial Catalog=myDataBase;User Id=myUsername;Password=myPassword;
      {
          SqlCommand cmd = new SqlCommand("Select Count(*) From jobs",cn);
          cn.Open();
%%2=cmd.ExecuteScalar(); //Message.InnerHtml
      }

2.单值比较
//using System.Data;
//using System.Data.SqlClient;
using (SqlConnection cn = new SqlConnection(%%1))
//ConfigurationManager.ConnectionStrings["db2ConnectionString"].ConnectionString
//Data Source=myServerAddress;Initial Catalog=myDataBase;User Id=myUsername;Password=myPassword;
      {
          SqlCommand cmd = new SqlCommand("Select Count(*) From jobs",cn);
          cn.Open();
%%2=cmd.ExecuteScalar(); //Message.InnerHtml
if(%%2==%%3)
{
%%4
}
      }

3.显示表格
//using System.Data;
//using System.Data.SqlClient;
DataSet ds=null;
using (SqlConnection cn = new SqlConnection(%%1))
//ConfigurationManager.ConnectionStrings["db2ConnectionString"].ConnectionString
//Data Source=myServerAddress;Initial Catalog=myDataBase;User Id=myUsername;Password=myPassword;
      {
          cn.Open();
cmd=new SqlDataAdapter("Select * From Author",cn);
ds=new DataSet();
cmd.Fill(ds,%%2); //"作者"
MyDataGrid.DataSource=ds.Tables(%%2).DefaultView; //"作者"
MyDataGrid.DataBind();
      }

4.操作表格
//using System.Data;
//using System.Data.SqlClient;
using (SqlConnection cn = new SqlConnection(%%1))
//ConfigurationManager.ConnectionStrings["db2ConnectionString"].ConnectionString
//Data Source=myServerAddress;Initial Catalog=myDataBase;User Id=myUsername;Password=myPassword;
      {
          cn.Open();
cmd=new SqlDataAdapter("Select * From Author",cn);
ds=new DataSet();
cmd.Fill(ds,%%2); //"作者"
MyDataGrid.DataSource=ds.Tables(%%2).DefaultView; //"作者"
MyDataGrid.DataBind();
      }

5.数值范围查询
//using System.Data;
//using System.Data.SqlClient;
using (SqlConnection cn = new SqlConnection(%%1))
//ConfigurationManager.ConnectionStrings["db2ConnectionString"].ConnectionString
//Data Source=myServerAddress;Initial Catalog=myDataBase;User Id=myUsername;Password=myPassword;
      {
 cn.Open();
int min = Int32.Parse(jcb1.selectedItem);
int max = Int32.Parse(jcb2.selectedItem);
cmd=new SqlDataAdapter("Select count(*) as pro_count From ProPrice where price between "
+ min + " and " + max,cn);
ds=new DataSet();
cmd.Fill(ds,%%2); //"作者"
MyDataGrid.DataSource=ds.Tables(%%2).DefaultView; //"作者"
MyDataGrid.DataBind();
      }

6.关闭时断开连接
//using System.Data;
//using System.Data.SqlClient;
using (SqlConnection cn = new SqlConnection(%%1))
//ConfigurationManager.ConnectionStrings["db2ConnectionString"].ConnectionString
//Data Source=myServerAddress;Initial Catalog=myDataBase;User Id=myUsername;Password=myPassword;
      {
      }

7.执行命令
//using System.Data;
//using System.Data.SqlClient;
using (SqlConnection cn = new SqlConnection(%%1))
//ConfigurationManager.ConnectionStrings["db2ConnectionString"].ConnectionString
//Data Source=myServerAddress;Initial Catalog=myDataBase;User Id=myUsername;Password=myPassword;
      {
          SqlCommand cmd = new SqlCommand("insert userRegister_t values('"
              + TextBox1.Text + "','" + TextBox2.Text + "')",cn);
          cn.Open();
          cmd.ExecuteNonQuery();
      }

7.Oracle8/8i/9i数据库(thin模式)
//using System.Data;
Oracle Set Your custom connection strings values

ODBC
New version
 
Driver={Microsoft ODBC for Oracle};Server=myServerAddress;Uid=myUsername;Pwd=myPassword;

Old version
 
Driver={Microsoft ODBC Driver for Oracle};ConnectString=OracleServer.world;Uid=myUsername;Pwd=myPassword;

OLE DB, OleDbConnection (.NET)
Standard security
This connection string uses a provider from Microsoft. 
Provider=msdaora;Data Source=MyOracleDB;User Id=myUsername;Password=myPassword;

Standard Security
This connection string uses a provider from Oracle. 
Provider=OraOLEDB.Oracle;Data Source=MyOracleDB;User Id=myUsername;Password=myPassword;

Trusted Connection
 
Provider=OraOLEDB.Oracle;Data Source=MyOracleDB;OSAuthent=1;

OracleConnection (.NET)
Standard
 
Data Source=MyOracleDB;Integrated Security=yes;

This one works only with Oracle 8i release 3 or later 
 
Specifying username and password
 
Data Source=MyOracleDB;User Id=myUsername;Password=myPassword;Integrated Security=no;

This one works only with Oracle 8i release 3 or later 
Missing the System.Data.OracleClient namespace? Download .NET Managed Provider for Oracle >>
Great article! "Features of Oracle Data Provider for .NET" by Rama Mohan G. at C# Corner >>
 
Omiting tnsnames.ora
This is another type of Oracle connection string that doesn't rely on you to have a DSN for the connection. You create a connection string based on the format used in the tnsnames.ora file without the need to actually have one of these files on the client pc. 
SERVER=(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=MyHost)(PORT=MyPort))(CONNECT_DATA=(SERVICE_NAME=MyOracleSID)));uid=myUsername;pwd=myPassword;

Core Labs OraDirect (.NET)
Standard
 
User ID=myUsername;Password=myPassword;Host=ora;Pooling=true;Min Pool Size=0;Max Pool Size=100;Connection Lifetime=0;

Read more at Core Lab >>
And at the product page >>
 
Data Shape
MS Data Shape
 
Provider=MSDataShape.1;Persist Security Info=False;Data Provider=MSDAORA;Data Source=orac;User Id=myUsername;Password=myPassword;

8.DB2数据库
string connString ="Server=myAddress:myPortNumber;Database=myDataBase;UID=myUsername;PWD=myPassword;";

9.SQL Server7.0/2000数据库
string connString ="Data Source=myServerAddress;Initial Catalog=myDataBase;User Id=myUsername;Password=myPassword;";
/*
Server=myServerAddress;Database=myDataBase;User ID=myUsername;Password=myPassword;Trusted_Connection=False;
*/
SQL Server2005数据库
string connString ="Data Source=myServerAddress;Initial Catalog=myDataBase;User Id=myUsername;Password=myPassword";
/*
Server=myServerAddress;Database=myDataBase;User ID=myUsername;Password=myPassword;Trusted_Connection=False;
*/

10.Sybase数据库
string connString ="Data Source='myASEserver';Port=5000;Database=myDataBase;Uid=myUsername;Pwd=myPassword;"; //Sybase Adaptive Server Enterprise
string connString ="Data Source=//myserver/myvolume/mypat/mydd.add;User ID=myUsername;Password=myPassword;ServerType=REMOTE;"; //Sybase Advantage Database Server

11.Informix数据库
string connString ="Database=myDataBase;Host=192.168.10.10;Server=db_engine_tcp;Service=1492; Protocol=onsoctcp;UID=myUsername;Password=myPassword;";

12.MySQL数据库
string connString ="Server=myServerAddress;Database=myDataBase;Uid=myUsername;Pwd=myPassword;";

13.PostgreSQL数据库
string connString ="User ID=root;Password=myPassword;Host=localhost;Port=5432;Database=myDataBase; Pooling=true;Min Pool Size=0;Max Pool Size=100;Connection Lifetime=0;";

14.连接access数据库
string connString ="Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:/mydatabase.mdb;User Id=admin;Password=;";

15.连接MySql数据库
string connString ="Server=myServerAddress;Database=myDataBase;Uid=myUsername;Pwd=myPassword;";

16.程序计时
    DateTime runTime = Convert.ToDateTime(System.Configuration.ConfigurationSettings.AppSettings["TimerRunAt"]);
    //运行时间
    TimeSpan runTime = new TimeSpan(runTime.Ticks);
    //现在时间
    TimeSpan timeNow = new TimeSpan(DateTime.Now.Ticks);
    //时间间隔
    TimeSpan ts = runTime.Subtract(timeNow);
    //如果运行时间与当前时间的差大于0,则任务执行时间为当日
    if(ts.TotalMilliseconds > 0) 
    {
        return ts.TotalMilliseconds;
    }
    //如果运行时间与当前时间的差小于0,则任务执行时间为次日
    Else
    {
        //差值的绝对值应加1天
        return ts.Duration().Add(new TimeSpan(1,0,0,0,0)).TotalMilliseconds;
    }

17.延时
//using System.Threading;
Thread.Sleep(Int32.Parse(%%1));

18.连接Excel文件
string connString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + excel文件名(绝对路径) +";Extended Properties=Excel 8.0;";

19.GDI+时钟
/*
using System.Data;
using System.Drawing;
using System.Drawing.Drawing2D;
*/
        private Point mickeyMouse = new Point(0, 0);
        private void Form1_Paint(object sender, PaintEventArgs e)
        {
            DrawClock(e.Graphics);
            timer1.Start();
        }

private void DrawClock(Graphics g)
        {
            ///centre(120, 130);
            Rectangle outRect = new Rectangle(0, 0, 240, 260);
            Rectangle midRect = new Rectangle(7, 7, 226, 246);
            Rectangle inRect = new Rectangle(10, 10, 220, 240);
 
            LinearGradientBrush outlBlueBrush = new LinearGradientBrush(outRect, Color.FromArgb(0, 0, 100),
                Color.FromArgb(0, 0, 255), LinearGradientMode.BackwardDiagonal);
            LinearGradientBrush midlBlueBrush = new LinearGradientBrush(midRect, Color.FromArgb(0, 0, 255),
                Color.FromArgb(0, 0, 100), LinearGradientMode.BackwardDiagonal);
            LinearGradientBrush inlBlueBrush = new LinearGradientBrush(inRect, Color.FromArgb(0, 0, 100),
               Color.FromArgb(0, 0, 255), LinearGradientMode.BackwardDiagonal);
 
            g.FillEllipse(outlBlueBrush, outRect);
            g.FillEllipse(midlBlueBrush, midRect);
            g.FillEllipse(inlBlueBrush, inRect);
 
            outlBlueBrush.Dispose();
            midlBlueBrush.Dispose();
            inlBlueBrush.Dispose();
 
            //
            Font myFont = new Font("Arial", 20, FontStyle.Bold);
            SolidBrush whiteBrush = new SolidBrush(Color.White);
            g.DrawString("12", myFont, whiteBrush, 100, 10);
            g.DrawString("6", myFont, whiteBrush, 110, 223);
            g.DrawString("3", myFont, whiteBrush, 210, 120);
            g.DrawString("9", myFont, whiteBrush, 10, 120);
            g.DrawString("1", myFont, whiteBrush, 160, 26);
            g.DrawString("2", myFont, whiteBrush, 194, 64);
            g.DrawString("5", myFont, whiteBrush, 156, 210);
            g.DrawString("4", myFont, whiteBrush, 192, 174);
            g.DrawString("11", myFont, whiteBrush, 55, 28);
            g.DrawString("10", myFont, whiteBrush, 22, 66);
            g.DrawString("7", myFont, whiteBrush, 64, 210);
            g.DrawString("8", myFont, whiteBrush, 28, 174);
 
            myFont.Dispose();
            whiteBrush.Dispose();
            //DateTime;
            g.TranslateTransform(120, 130, MatrixOrder.Append);
 
            //
            Pen hourPen = new Pen(Color.White, 6);
            hourPen.SetLineCap(LineCap.RoundAnchor, LineCap.ArrowAnchor, DashCap.Flat);
            Pen minutePen = new Pen(Color.White, 4);
            minutePen.SetLineCap(LineCap.RoundAnchor, LineCap.ArrowAnchor, DashCap.Flat);
            Pen secondPen = new Pen(Color.Red, 2);
 
            int sec = DateTime.Now.Second;
            int min = DateTime.Now.Minute;
            int hour = DateTime.Now.Hour;
 
            double secondAngle = 2.0 * Math.PI * sec / 60.0;
            double minuteAngle = 2.0 * Math.PI * (min + sec / 60.0) / 60.0;
            double hourAngle = 2.0 * Math.PI * (hour + min / 60.0) / 12.0;
 
            Point centre = new Point(0, 0);
 
            Point hourHand = new Point((int)(40 * Math.Sin(hourAngle)),
            (int)(-40 * Math.Cos(hourAngle)));
            g.DrawLine(hourPen, centre, hourHand);
 
            Point minHand = new Point((int)(80 * Math.Sin(minuteAngle)),
            (int)(-80 * Math.Cos(minuteAngle)));
            g.DrawLine(minutePen, centre, minHand);
 
            Point secHand = new Point((int)(80 * Math.Sin(secondAngle)),
            (int)(-80 * Math.Cos(secondAngle)));
            g.DrawLine(secondPen, centre, secHand);
 
            hourPen.Dispose();
            minutePen.Dispose();
            secondPen.Dispose();
        }
 
        private void timer1_Tick(object sender, EventArgs e)
        {
            this.Invalidate();             
        }

private void hideToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (contextMenuStrip1.Items[0].ToString() == "Hide")
            {
                this.Hide();
                contextMenuStrip1.Items[0].Text = "Show";
                return;
            }
 
            if (contextMenuStrip1.Items[0].ToString() == "Show")
            {
                this.Show();
                contextMenuStrip1.Items[0].Text = "Hide";
                return;
            }
        }
 
        private void Form1_MouseDown(object sender, MouseEventArgs e)
        {
            mickeyMouse = new Point(-e.X, -e.Y);
        }
 
        private void Form1_MouseMove(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                Point mousePos = Control.MousePosition;
                mousePos.Offset(mickeyMouse.X, mickeyMouse.Y);
                Location = mousePos;
            }
        }
 
        private void notifyIcon1_DoubleClick(object sender, EventArgs e)
        {
            if (contextMenuStrip1.Items[0].ToString() == "Show")
            {
                this.Show();
                contextMenuStrip1.Items[0].Text = "Hide";
                return;
            }
        }

20.数据库存入二进制字段数据
/*
using System.Data;
using System.IO;
using System.Data.SqlClient;
*/
private string File="";
if(openFileDialog1.ShowDialog()==DialogResult.OK)
{
pictureBox1.Image=new Bitmap(openFileDialog1.FileName);
FileName=openFileDialog1.FileName;
}
try{
DataSet ds=new DataSet();
sqlDataAdapter1.Fill(ds,%%1); //"db"
DataTable MyTable=ds.Tables[0];
DataRow MyRow=MyTable.Rows.Count+1;
MyRow[%%2]=MyTable.NewRow(); //"id"
MyRow[%%3]=%%5; //"FileName"
MyRow[%%4]=%%6; //"Description"
FileStream fs=new FileStream(FileNmae,FileMode.OpenOrCreate,FileAccess.Read);
byte[] MyData=new byte[fs.Length];
fs.Read(MyData,0,(int)fs.Length);
MyRow[%%7[=MyData; //"FileData"
MyTable.Rows.Add(MyRow);
sqlDataAdapter1.Update(ds,%%1);
ds.AcceptChanges();
//存储成功
}
catch(Exception ex)
{
//ex.Message.ToString()
}

21.数据库取出二进制字段数据
/*
using System.Data;
using System.IO;
*/
private int index=1;
private System.Windows.Forms.BindingManagerBase_Bind();
private DataSet ds=new DataSet();
sqlDataAdapter1.Fill(ds,%%1); //"db"
_Bind=BindingContext[ds,%%1];
textBox1.DataBindings.Add("Text",ds,"%%1.%%3"); //filename
textBox2.DataBindings.Add("Text",ds,"%%1.%%4"); //description
if(_Bind.Count!=0)
{
try{
if(pictureBox1.Image!=null)
pictureBox1.Image.Dispose();
pictureBox1.Image=null;
sqlDataAdapter1.SelectCommand.CommandText="Select * From %%1 Where %%2="+Convert.ToString(index); //id
DataSet dataSet=new DataSet();
sqlDataAdapter1.Fill(dataSet,%%1);
byte[] MyData=(byte[])dataSet.Tables[0].Rows[0][%%5]; //"FileData"
Int32 size=MyData.GetUpperBound(0);
FileStream fs=new FileStream(%%6,FileMode.OpenOrCreate,FileAccess.Wrtie); //"temp.bmp"
fs.Write(MyData,0,size+1);
fs.Close();
pictureBox1.Image=new Bitmap(%%6);
}
catch(Exception ex)
{
//ex.Message.ToString()
}
}

c#数据库操作大全的更多相关文章

  1. 【转】sql server数据库操作大全——常用语句/技巧集锦/经典语句

    本文为累计整理,有点乱,凑合着看吧! ☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆ ☆ ☆ ☆ sql 宝 典 ☆ ☆ ☆ 2012年-8月 修订版 ☆ ...

  2. Java数据库操作大全

    1.提取单条记录 //import java.sql.*; Connection con=null; Statement stmt=null; ResultSet %%6=null; try { Cl ...

  3. jsp数据库连接大全和数据库操作封装到Javabean

    一.jsp连接Oracle8/8i/9i数据库(用thin模式) testOracle.jsp如下: <%@ page contentType="text/html;charset=g ...

  4. (转载)常用的Mysql数据库操作语句大全

    打开CMD,进入数据库命令:mysql -hlocalhost -uroot -p 退出数据库:exit 用户管理: 1.新建用户: >CREATE USER name IDENTIFIED B ...

  5. 常用的Mysql数据库操作语句大全

    一.用户管理: 1.新建用户: >CREATE USER name IDENTIFIED BY 'ssapdrow'; 2.更改密码: >SET PASSWORD FOR name=PAS ...

  6. 零、常用的Mysql数据库操作语句大全

    零.用户管理: 1.新建用户: >CREATE USER name IDENTIFIED BY 'ssapdrow'; 2.更改密码: >SET PASSWORD FOR name=PAS ...

  7. 数据库操作语句大全(sql)

    一.基础 1.说明:创建数据库CREATE DATABASE database-name 2.说明:删除数据库drop database dbname3.说明:备份sql server--- 创建 备 ...

  8. Oracle 数据库语句大全

    Oracle数据库语句大全 ORACLE支持五种类型的完整性约束 NOT NULL (非空)--防止NULL值进入指定的列,在单列基础上定义,默认情况下,ORACLE允许在任何列中有NULL值. CH ...

  9. Delphi Excel 操作大全

    Delphi Excel 操作大全 (一) 使用动态创建的方法首先创建 Excel 对象,使用ComObj:var ExcelApp: Variant;ExcelApp := CreateOleObj ...

随机推荐

  1. HYSBZ 2243 染色 (树链拆分)

    主题链接~~> 做题情绪:这题思路好想.调试代码调试了好久.第一次写线段树区间合并. 解题思路: 树链剖分 + 线段树区间合并 线段树的端点记录左右区间的颜色.颜色数目.合并的时候就用区间合并的 ...

  2. c# 在cmd中用 7z解压缩文件

    var exePath = @"C:\Program Files\7-Zip\7z.exe"; var path = @"I:\work\MusicCatcher2\Wi ...

  3. 无显示仍然发挥树莓派——VNCserver设定

    谁说没有显示器就不能玩树莓派的图形界面了.不要忘了VNCserver哦! VNC(Virtual Network Computing)属于一种网络显示系统,也就是说它能将完整的窗体界面通过网络传输到还 ...

  4. C#内存分配学习

    CLR内存分配分三大块区域:栈.GC堆.大对象堆. 一.线程堆栈(栈) 用于分配值类型实例.栈由操作系统进行管理,不受GC管理,当值类型不在其作用域(主要是指其所在函数内)时,其所占栈空间自动释放.栈 ...

  5. ignore,neglect,omit,overlook

    一:简介——ignore :通常指有意不顾,或不理显而易见的事物.neglect :侧重指有意的忽略或忽视,也可指粗心与疏忽.omit :指有意或无意地忘记做某事,也指删去被视作不重要.不合意的东西. ...

  6. Android之Handler的postDelayed()使用方法

    这是一种创建多线程信息功能 用法: 1,首先创建一个Handler物 Handler handler=new Handler(); 2.然后创建一个Runnable物 Runnable runnabl ...

  7. AspNet MVC4 教育-28:Asp.Net MVC4 Ajax技术部门四舍五入余速Demo

    A.创建一个Basic项目类型. B.于Models创建一个文件夹: DivModel.cs: using System; using System.Collections.Generic; usin ...

  8. ORA-01791: not a SELECTed expression 一种是不 bug 的 bug!

    [ora11@lixora ~]$ !sql sqlplus / as sysdba SQL*Plus: Release 11.2.0.1.0 Production on Wed Aug 27 09: ...

  9. Linking pronunciation in English

    1.constant+vowel stand up give up get up 2.vowel+vowel 2.1 i:/i/ei/ai/oi [j] stay up carry it 2.2 u: ...

  10. 读改善c#代码157个建议:建议4~6

    目录: 建议4:TryParse比Parse好 建议5:使用int?确保值类型也可以为null 建议6:区别 readonly 和 const 的用法 一.建议4:TryParse比Parse 好 T ...