I have a for each loop that will not stop inserting into sql server.
Here is my code:
using System;
using System.Threading;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Google.Apis.Analytics.v3;
using Google.Apis.Analytics.v3.Data;
using Google.Apis.Services;
using System.Security.Cryptography.X509Certificates;
using Google.Apis.Auth.OAuth2;
using System.Data.SqlClient;
using System.Configuration;
namespace GooAnalyzer
{
class Program
{
static void RunSecondSite()
{
var serviceAccountEmail = "543652534806-7lk19u13619g9pthghqger31sth9jpr4#developer.gserviceaccount.com";
var certificate = new X509Certificate2(#"C:\Key\key.p12", "notasecret", X509KeyStorageFlags.Exportable);
var credential = new ServiceAccountCredential(
new ServiceAccountCredential.Initializer(serviceAccountEmail)
{
Scopes = new[] { AnalyticsService.Scope.Analytics }
}.FromCertificate(certificate));
// Create the service.
//Twistandtango
var gas = new AnalyticsService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = "GooAnalyzer",
});
var r = gas.Data.Ga.Get("ga:1860066", "2014-12-27", "2015-01-10", "ga:totalValue");
//Specify some addition query parameters
r.Dimensions = "ga:source,ga:medium,ga:campaign,ga:transactionId,ga:date";
r.MaxResults = 100000000;
//Execute and fetch the results of our query
Google.Apis.Analytics.v3.Data.GaData d = r.Execute();
foreach (var h in d.ColumnHeaders)
{
SqlConnection sqlCon = new SqlConnection("Data Source=UNDERGOD-PC\\SQLEXPRESS;Initial Catalog=GooAnalyzer;Integrated Security=True");
sqlCon.Open();
foreach (var row in d.Rows)
{
using (SqlCommand sqlCmd1 = new SqlCommand { CommandText = "INSERT INTO [GooData] ([Website], [gasource], [gamedium], [gacampaign], [gatransactionid], [gadate], [gatotalvalue], [Timeinserted]) VALUES (#Website, #gasource, #gamedium, #gacampaign, #gatransactionid, #gadate, #gatotalvalue, #Timeinserted)", Connection = sqlCon })
{
sqlCmd1.Parameters.AddWithValue("#Website", "4wheelparts.com");
sqlCmd1.Parameters.AddWithValue("#gasource", row[0]);
sqlCmd1.Parameters.AddWithValue("#gamedium", row[1]);
sqlCmd1.Parameters.AddWithValue("#gacampaign", row[2]);
sqlCmd1.Parameters.AddWithValue("#gatransactionid", row[3]);
sqlCmd1.Parameters.AddWithValue("#gadate", row[4]);
sqlCmd1.Parameters.AddWithValue("#gatotalvalue", row[5]);
sqlCmd1.Parameters.AddWithValue("#Timeinserted", DateTime.Now.ToString("MM-dd-yyyy"));
sqlCmd1.ExecuteNonQuery();
}
}
sqlCon.Close();
}
}
static void Main(string[] args)
{
var serviceAccountEmail = "543652534806-7lk19u13619g9pthghqger31sth9jpr4#developer.gserviceaccount.com";
var certificate = new X509Certificate2(#"C:\Key\key.p12", "notasecret", X509KeyStorageFlags.Exportable);
var credential = new ServiceAccountCredential(
new ServiceAccountCredential.Initializer(serviceAccountEmail)
{
Scopes = new[] { AnalyticsService.Scope.Analytics }
}.FromCertificate(certificate));
// Create the service.
//Twistandtango
var gas = new AnalyticsService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = "GooAnalyzer",
});
var r = gas.Data.Ga.Get("ga:1381000", "2014-12-27", "2015-01-10", "ga:totalValue");
//Specify some addition query parameters
r.Dimensions = "ga:source,ga:medium,ga:campaign,ga:transactionId,ga:date";
r.MaxResults = 100000000;
//Execute and fetch the results of our query
Google.Apis.Analytics.v3.Data.GaData d = r.Execute();
Console.WriteLine("Starting...");
foreach (var h in d.ColumnHeaders)
{
SqlConnection sqlCon = new SqlConnection("Data Source=UNDERGOD-PC\\SQLEXPRESS;Initial Catalog=GooAnalyzer;Integrated Security=True");
sqlCon.Open();
foreach (var row in d.Rows)
{
using (SqlCommand sqlCmd1 = new SqlCommand { CommandText = "INSERT INTO [GooData] ([Website], [gasource], [gamedium], [gacampaign], [gatransactionid], [gadate], [gatotalvalue], [Timeinserted]) VALUES (#Website, #gasource, #gamedium, #gacampaign, #gatransactionid, #gadate, #gatotalvalue, #Timeinserted)", Connection = sqlCon })
{
sqlCmd1.Parameters.AddWithValue("#Website", "4wd.com");
sqlCmd1.Parameters.AddWithValue("#gasource", row[0]);
sqlCmd1.Parameters.AddWithValue("#gamedium", row[1]);
sqlCmd1.Parameters.AddWithValue("#gacampaign", row[2]);
sqlCmd1.Parameters.AddWithValue("#gatransactionid", row[3]);
sqlCmd1.Parameters.AddWithValue("#gadate", row[4]);
sqlCmd1.Parameters.AddWithValue("#gatotalvalue", row[5]);
sqlCmd1.Parameters.AddWithValue("#Timeinserted", DateTime.Now.ToString("MM-dd-yyyy"));
sqlCmd1.ExecuteNonQuery();
}
}
sqlCon.Close();
RunSecondSite();
}
}
}
}
The code continues to loop when i run this:
RunSecondSite();
It will keep on inserting and I do not know how to stop it or where to place the correct breaks.
I want to call more methods of this code in the console application later using the same for each loop as well.
Please advise.
Your current logic is that you are adding each row to the database, each time you iterate over the column headers, resulting in identical rows being inserted.
From your code, it appears that "h" is never being used..
Simply remove:
foreach (var h in d.ColumnHeaders)
{
...
}
to become:
SqlConnection sqlCon = new SqlConnection("Data Source=UNDERGOD-PC\\SQLEXPRESS;Initial Catalog=GooAnalyzer;Integrated Security=True");
sqlCon.Open();
foreach (var row in d.Rows)
{
using (SqlCommand sqlCmd1 = new SqlCommand { CommandText = "INSERT INTO [GooData] ([Website], [gasource], [gamedium], [gacampaign], [gatransactionid], [gadate], [gatotalvalue], [Timeinserted]) VALUES (#Website, #gasource, #gamedium, #gacampaign, #gatransactionid, #gadate, #gatotalvalue, #Timeinserted)", Connection = sqlCon })
{
sqlCmd1.Parameters.AddWithValue("#Website", "4wheelparts.com");
sqlCmd1.Parameters.AddWithValue("#gasource", row[0]);
sqlCmd1.Parameters.AddWithValue("#gamedium", row[1]);
sqlCmd1.Parameters.AddWithValue("#gacampaign", row[2]);
sqlCmd1.Parameters.AddWithValue("#gatransactionid", row[3]);
sqlCmd1.Parameters.AddWithValue("#gadate", row[4]);
sqlCmd1.Parameters.AddWithValue("#gatotalvalue", row[5]);
sqlCmd1.Parameters.AddWithValue("#Timeinserted", DateTime.Now.ToString("MM-dd-yyyy"));
sqlCmd1.ExecuteNonQuery();
}
}
sqlCon.Close();
I think you simply need to replace
foreach (var h in d.ColumnHeaders)
{
SqlConnection sqlCon = ...
sqlCon.Open();
... // snip
sqlCon.Close();
}
with:
using(SqlConnection sqlCon = ...)
{
sqlCon.Open();
... // snip
sqlCon.Close();
}
Currently you are inserting all rows separately and identically for every column-header.
Related
I have 3 input (username,password and datasource) and a button (connect) by clicking on button list of bank in db will be demonstrate
\[HttpGet\]
public JsonResult search()
{
//try connect to make connection on sql engine
// if it could to connect get list of db and return
// that
var username = Request.QueryString["username"].ToString();
var password = Request.QueryString["password"].ToString();
var datasource = Request.QueryString["databaseConString"].ToString();
SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder();
builder["Server"] = datasource;
builder["Connect Timeout"] = 1000;
builder["Trusted_Connection"] = true;
builder["Integrated Security"] = false;
builder.Password = password;
builder.UserID = username;
List<string> list = new List<string>();
Console.WriteLine(builder.ConnectionString);
using (SqlConnection con = new SqlConnection(builder.ConnectionString))
{
con.Open();
using (SqlCommand cmd = new SqlCommand(" **problem **SELECT name FROM sys.databases**"**,con))
{
using (SqlDataReader dr = cmd.ExecuteReader())
{
// # I have problem in this loop **
while (dr.Read())
{
//list.Add(dr.GetString());
Console.WriteLine("{0}",dr[0]);
}
//foreach(var item in list)
//{
// Console.WriteLine(list);
//}
}
return Json( JsonRequestBehavior.AllowGet);
}
}
}
I do not know How use sqlDataReader and add object to my list
**problem SELECT name FROM sys.databases
Here you should also need to know in which table under the database, you are going to search bank name you haven't specified that. For instance, you should write like beloww:
SELECT BankName FROM BankTable [dbo].[BankDatabase]
I do not know How use sqlDataReader and add object to my list
Well, you could fetch your database-entity from your table inside the while loop. Finally bind your property into your list. Your code should be as following:
[HttpGet]
public JsonResult search()
{
var username = Request.QueryString["username"].ToString();
var password = Request.QueryString["password"].ToString();
var datasource = Request.QueryString["databaseConString"].ToString();
SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder();
builder["Server"] = datasource;
builder["Connect Timeout"] = 1000;
builder["Trusted_Connection"] = true;
builder["Integrated Security"] = false;
builder.Password = password;
builder.UserID = username;
List<string> listData = new List<string>();
using (SqlConnection con = new SqlConnection(builder.ConnectionString))
{
con.Open();
using (SqlCommand cmd = new SqlCommand("SELECT [BankName] FROM [DataBaseName].[dbo].[TableName]", con))
{
using (SqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
string bankName = reader.GetString(0);
listData.Add(bankNamee);
}
}
return Json(listData);
}
}
}
Note: Make sure reader.GetString(0) the order has followed accordingly. Means if the [BankName] is in first order theb it should be as reader.GetString(0). In addition, remember the data-type as well. For your information, here, I am getting each bankNamee and binding to the list I defined above listData.Add(bankNamee);
Output:
I am getting Not all variables Bound.
Here is what My Code Looks Like.
public IEnumerable<VaultService> Get(string Branch_Desg)
{
OracleConnection con = new OracleConnection(constr);
con.Open();
DataTable dt = new DataTable();
//string sql = "select * from wemadummyvaulttable where branch_desg = " + Branch_Desg + "";
string sql = "select BRANCH_ID ,BRANCH_NAME ,BRANCHID_NUMBER ,BRANCH_ACCOUNTNO ,BRANCH_DESG ,CURRENCY ,BRANCH_BALANCE from wemadummyvaulttable where Branch_Desg =" + ":Branch_Desg";
OracleDataAdapter da = new OracleDataAdapter(sql, con);
da.Fill(dt);
List<VaultService> vr = new List<Models.VaultService>(dt.Rows.Count);
if (dt.Rows.Count > 0)
{
foreach (DataRow vaultrecord in dt.Rows)
{
vr.Add(new ReadVaultBal(vaultrecord));
}
}
return vr;
}
For some Reason its not Working like its supposed to.
Screenshot Looks Like this :
Now My Updated Code Looks like this:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using WEMAVaultREST.Models;
using Oracle.ManagedDataAccess.Client;
using Oracle.ManagedDataAccess.Types;
using System.Data;
namespace WEMAVaultREST.Controllers
{
public class VaultServiceController : ApiController
{
string constr = "User ID=system; Password=admin1234; Data Source=SAM;";
// GET api/<controller>
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
// GET api/<controller>/5
public string Get(int id)
{
return "value";
}
// GET api/<controller>/5
/* public VaultService Get(string Branch_Desg)
{
OracleConnection con = new OracleConnection(constr);
con.Open();
DataTable dt = new DataTable();
string sql = "select * from wemadummyvaulttable where branch_desg = '"+Branch_Desg+"'";
OracleDataAdapter da = new OracleDataAdapter(sql,con);
da.Fill(dt);
if (dt.Rows.Count > 0)
{
return new ReadVaultBal(dt.Rows[0]);
}
throw new Exception("Account not found");
}*/
public IEnumerable<VaultService> Get(string Branch_Desg)
{
OracleConnection con = new OracleConnection(constr);
con.Open();
DataTable dt = new DataTable();
//string sql = "select * from wemadummyvaulttable where branch_desg = " + Branch_Desg + "";
string sql = "select BRANCH_ID ,BRANCH_NAME ,BRANCHID_NUMBER ,BRANCH_ACCOUNTNO ,BRANCH_DESG ,CURRENCY ,BRANCH_BALANCE from wemadummyvaulttable where Branch_Desg =" + ":Branch_Desg";
var command = new OracleCommand(sql, con);
command.Parameters.Add("Branch_Desg", Branch_Desg);
OracleDataAdapter da = new OracleDataAdapter(command);
da.Fill(dt);
List<VaultService> vr = new List<Models.VaultService>(dt.Rows.Count);
if (dt.Rows.Count > 0)
{
foreach (DataRow vaultrecord in dt.Rows)
{
vr.Add(new ReadVaultBal(vaultrecord));
}
}
return vr;
}
// POST api/<controller>
public void Post([FromBody]string value)
{
}
// PUT api/<controller>/5
public void Put(int id, [FromBody]string value)
{
}
// DELETE api/<controller>/5
public void Delete(int id)
{
}
}
}
Thats what i have for now. As you can see it Returns in Sqldeveloper.In the Code, it does not. I do not know what and where to Go from here.
If i run the REST api just like this :
http://localhost:7177/api/VaultService?Branch_Desg=Branch01
It returns this
Try replacing the line
OracleDataAdapter da = new OracleDataAdapter(sql, con);
with
var command = new OracleCommand(sql, con);
command.Parameters.Add("Branch_Desg", branchDesg);
OracleDataAdapter da = new OracleDataAdapter(command);
It seems there isn't a way to add bind parameters directly to an OracleDataAdapter, so we have to create an OracleCommand from the SQL string first, add a value for the parameter :Branch_Desg, and then create the adapter from the command.
Finally, can I please recommend that all Oracle resources (connection, command and data-adapter) are disposed correctly, by creating them in using blocks, e.g.
using (OracleConnection con = new OracleConnection(constr))
{
// code using the database connection 'con'
}
So method GetAllData is one of my universal methods for connecting to the database and here, since I have to add mupltiple records in once to the database I need to have one connetion with multiple commands to run. So my question is does this way of connection closes the database correctly, or if you have any improvments to my code please share with me.
var conn = new SqlConnection(ConnString);
conn.Open();
var data = new Dictionary<string, List<object>>();
foreach (var h in hours)
{
data += SqlUniversal.GetAllData(query,//idk how I will collect the data yet... i know += wouldnt work for dictionary
new[] {
//some parameters
},
conn);
}
//Here is the method, above is how I call it.
public static Dictionary<string, List<object>> GetAllData(string command, SqlParameter[] pars, SqlConnection conn)
{
if (conn == null)
{
conn = new SqlConnection(ConnString);
conn.Open();
}
var res = new Dictionary<string, List<object>>();
using (conn)
{
using (var cmd = new SqlCommand(command, conn))
{
cmd.Parameters.AddRange(pars);
using (var reader = cmd.ExecuteReader())
{
while (reader.Read())
for (var i = 0; i < reader.VisibleFieldCount; i++)
{
if (reader.GetValue(i) == DBNull.Value)
continue;
var name = reader.GetName(i);
if (res.ContainsKey(name))
res[name].Add(reader.GetValue(i));
else
res.Add(name, new List<object> {reader.GetValue(i)});
}
return res;
}
}
}
}
Probably the better way to do this is to let the overseeing method manage the connection:
public void SomeDataMethod()
{
using (var conn = new SqlConnection(ConnString))
{
conn.Open();
var data = new Dictionary<string, List<object>>();
foreach (var h in hours)
{
data += SqlUniversal.GetAllData(query,
new[] {
//some parameters
},
conn);
}
}
}
And remove the using (conn) from the GetData method:
public static Dictionary<string, List<object>> GetAllData(string command, SqlParameter[] pars, SqlConnection conn)
{
var res = new Dictionary<string, List<object>>();
using (var cmd = new SqlCommand(command, conn))
{
cmd.Parameters.AddRange(pars);
using (var reader = cmd.ExecuteReader())
{
//...
return res;
}
}
}
Now SomeDataMethod controls the connection lifetime and GetData doesn't worry about connection management.
I am trying to use SqlBulkCopy with ServiceStack Ormlite and have written the below extension method:
public static void BulkInsertSqlServer<T>(this IDbConnection dbConn, string targetTable, IEnumerable<T> data, params string[] columns)
{
Ensure.NotNull(dbConn);
Ensure.That(dbConn.State == ConnectionState.Open);
Ensure.NotNullOrEmptyOrWhiteSpace(targetTable);
Ensure.NotNull(data);
Ensure.NotNullOrEmpty(columns);
var sqlConnection = dbConn as SqlConnection;
using (var bcp = new SqlBulkCopy(sqlConnection))
using (var reader = ObjectReader.Create(data, columns))
{
bcp.BatchSize = data.Count();
bcp.DestinationTableName = targetTable;
bcp.WriteToServer(reader);
}
}
Which I am using by:
_connFactory = new OrmLiteConnectionFactory(connStr, SqlServerOrmLiteDialectProvider.Instance);
using (var db = _connFactory.Open())
using (var tran = db.BeginTransaction())
{
db.BulkInsertSqlServer("User", users, "Name", "Age");
var allRoles = new List<Role>();
foreach (var listOfRoles in users.Select(d => d.Roles))
{
allRoles.AddRange(listOfRoles);
}
db.BulkInsertSqlServer("Role", allRoles, "Name", "UserId", "IsAdmin");
tran.Commit();
}
However sqlConnection is always null, any ideas?
Because the connection is wrapped in a managed OrmLiteConnectionWrapper, you can get the SqlConnection with:
var adoNetConn = ((IHasDbConnection)dbConn).DbConnection;
var sqlConnection = adoNetConn as SqlConnection;
Im new to using ASP.NET and would like to know how I can select a random row from a sql database and then display the fields in a html table on a separate page. It is intended that the user can press on button which will retrieve a random movie from the database and then display the movie details in a html table on a new page. I am not sure how to go about this and have been trying to use labels to display the data. Here is a sample of the code so far:
private SqlConnection conn;
protected void Page_Load(object sender, EventArgs e)
{
ConnectionStringSettings connString = ConfigurationManager.ConnectionStrings ["MovieAppConnectionString1"];
conn = new SqlConnection(connString.ConnectionString);
}
protected void ImageButton1_Click(object sender, ImageClickEventArgs e)
{
try
{
conn.Open();
string queryString = "SELECT TOP 1 * FROM Movie ORDER BY NEWID()";
SqlCommand cmd = new SqlCommand(queryString, conn);
{
SqlDataReader reader = cmd.ExecuteReader();
StringBuilder MyStringBuilder = new StringBuilder();
while (reader.Read())
{
Image2.Text = reader[2].ToString();
Label1.Text = reader[1].ToString();
Desc.Text = reader[3].ToString();
Direc.Text = reader[5].ToString();
Strs.Text = reader[7].ToString();
Rtime.Text = reader[4].ToString();
ImdbRt.Text = reader[8].ToString();
}
}
}
finally
{
conn.Close();
}
Server.Transfer("MovieSelected.aspx");
Change your sql server query from :
SELECT TOP 1 * FROM Movie ORDER BY NEWID()
to
SELECT TOP 1 * FROM Movie ORDER BY RAND()
In your aspx.cs file:
int iLength = 0;
int index = 0;
DataTable dt = new DataTable();
dt = SqlComm.SqlDataTable("SELECT * FROM Movie");
object obj = new object();
obj = SqlComm.SqlReturn("SELECT COUNT (yourTargetColumn) FROM yourTable");
if (obj != null)
iLength = Convert.ToInt32(obj);
string[] stringArray = new string[iLength];
for (index = 0; index < iLength; index++)
{
stringArray[index] = (string)dt.Rows[index]["yourTargetColumn"];
}
foreach (string strArray in stringArray)
{
Label yourLabel = new Label();
PH.Controls.Add(yourLabel);
}
In your .aspx file:
<asp:PlaceHolder ID="PH" runat="server"></asp:PlaceHolder>
Add a class to your App_Code folder named "SqlComm.cs":
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Data.SqlClient;
public class SqlComm
{
static string DatabaseConnectionString = "your connection string";
public static object SqlReturn(string sql)
{
using (SqlConnection conn = new SqlConnection(DatabaseConnectionString))
{
conn.Open();
SqlCommand cmd = new SqlCommand(sql, conn);
object result = (object)cmd.ExecuteScalar();
return result;
}
}
public static DataTable SqlDataTable(string sql)
{
using (SqlConnection conn = new SqlConnection(DatabaseConnectionString))
{
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.Connection.Open();
DataTable TempTable = new DataTable();
TempTable.Load(cmd.ExecuteReader());
return TempTable;
}
}
Note: Do not forget to add the using System.Data.SqlClient to your code. Also, you just have to customize the SELECT command in order to get the data you want.