Insert value in cassandra columnfamily in c#.net - asp.net-mvc-4

I face problem for inserting value in Cassandra database.
Please suggest me some code for inserting value in database
var empRecord = new EmployeeEntity()
{
employeeid=2,
age=23,
employeename=txtName.Text,
salary=5001
};
var employeeRecord = new CassandraEntity<List<Column>>().SetColumnFamily(columnFamily).SetKey(empRecord.employeeid).SetData(empRecord);
ctx.ColumnList.InsertOnSubmit(employeeRecord);
ctx.SubmitChanges();
i getting error for inserting value in Cassandra database
Error like -> Not enough bytes to read value of component 0
How to solve it

I'm not sure which driver you are trying to use, but this works with the DataStax C# CQL3 driver.
First, connect to Cassandra and get your session:
cluster = Cluster.Builder().WithCredentials(_user, _password).AddContactPoint(_node).Build();
Session session = cluster.Connect();
Then, insert data using the following:
String strCQL1 = "UPDATE yourKeyspaceName.employee SET age=?, "
+ "employeename=?, Salary=? "
+ "WHERE employeeid=?";
PreparedStatement statement = session.Prepare(strCQL1);
BoundStatement boundStatement = new BoundStatement(statement);
boundStatement.Bind(age, txtName.Text, salary, empRecord.employeeid);
session.Execute(boundStatement);
In this case, Cassandra will perform an "UPSERT," inserting the data if it does not exist and updating if it does. Just make sure that your primary key(s) are in the WHERE clause.

Try This solution ,
string query = " insert into employee (employeeid,age,employeename,salary) values (" + txtId.Text + ",31,'" + strNameHex.Trim() + "'," + myHexNumber + ")";
txtQuery.Text = query;
context.ExecuteNonQuery(query);
context.SaveChanges();
It's help you

Related

MERGE INTO multiple statements at once Oracle SQL

I have a merge into statement as this :
private static final String UPSERT_STATEMENT = "MERGE INTO " + TABLE_NAME + " tbl1 " +
"USING (SELECT ? as KEY,? as DATA,? as LAST_MODIFIED_DATE FROM dual) tbl2 " +
"ON (tbl1.KEY= tbl2.KEY) " +
"WHEN MATCHED THEN UPDATE SET DATA = tbl2.DATA, LAST_MODIFIED_DATE = tbl2.LAST_MODIFIED_DATE " +
"WHEN NOT MATCHED THEN " +
"INSERT (DETAILS,KEY, DATA, CREATION_DATE, LAST_MODIFIED_DATE) " +
"VALUES (SEQ.NEXTVAL,tbl2.KEY, tbl2.DATA, tbl2.LAST_MODIFIED_DATE,tbl2.LAST_MODIFIED_DATE)";
This is the execution method:
public void mergeInto(final JavaRDD<Tuple2<Long, String>> rows) {
if (rows != null && !rows.isEmpty()) {
rows.foreachPartition((Iterator<Tuple2<Long, String>> iterator) -> {
JdbcTemplate jdbcTemplate = jdbcTemplateFactory.getJdbcTemplate();
LobCreator lobCreator = new DefaultLobHandler().getLobCreator();
while (iterator.hasNext()) {
Tuple2<Long, String> row = iterator.next();
String details = row._2();
Long key = row._1();
java.sql.Date lastModifiedDate = Date.valueOf(LocalDate.now());
Boolean isSuccess = jdbcTemplate.execute(UPSERT_STATEMENT, (PreparedStatementCallback<Boolean>) ps -> {
ps.setLong(1, key);
lobCreator.setBlobAsBytes(ps, 2, details.getBytes());
ps.setObject(3, lastModifiedDate);
return ps.execute();
});
System.out.println(row + "_" + isSuccess);
}
});
}
}
I need to upsert multiple of this statement inside of PLSQL, bulks of 10K if possible.
what is the efficient way to save time : execute 10K statements at once, or how to execute 10K statements in the same transaction?
how should I change the method for support it?
Thanks,
Me
the most efficient way would be one that bulk-loads your data into the database. In comparison to one-by-one uploads (as in your example), I'd expect performance gains of at least 1 or 2 orders of magnitude ("bigger" data means less to be gained by bulk-inserting).
you could use a technique as described in this answer to bulk-insert your records into a temporary table first and then perform a single merge statement using the temporary table.

SQL String or binary data would be truncated

I'm trying to search the max ID in the database, then increment it by 1 for each new entry as shown below:
var query2 = dbb.Database.SqlQuery<patient_visit>("SELECT MAX(CAST(SUBSTRING(pvid, 3, 10) AS int)) FROM patient_visit");
if (query2 != null)
{
objDetails.pvid = query2.ToString();
objDetails.pvid += 1;
objDetails.pvid = "PV" + objDetails.pvid;
}
string sql = "INSERT INTO patient_visit (pvid,paid) " +
"VALUES('" + objDetails.pvid + "', '" + paid + "')";
But when i try to insert it in the database, it gives out error
An exception of type 'System.Data.SqlClient.SqlException' occurred in EntityFramework.SqlServer.dll but was not handled in user code
Additional information: String or binary data would be truncated.
I've tried running the query in SQL Server and checked the value of 'pvid', it is 10 so after i include 'PV' to the integer pvid, it should be 12. So it should be fine, but why did i get that error? Please can anyone help me?
[Key]
[MaxLength(20), MinLength(12)]
public string pvid { get; set; }
When i replace the pvid with hard code ID, it works just fine. Why is this happening?
P/S: I know its not advisable to simply concatenate the input data with the query, but i've also tried querying using parameterized query but it gives same error.
string sql = "INSERT INTO patient_visit (pvid,paid) " +
"VALUES(#pvid, #paid)";
List<SqlParameter> parameterList = new List<SqlParameter>();
parameterList.Add(new SqlParameter("#pvid", objDetails.pvid));
parameterList.Add(new SqlParameter("#paid", paid));
SqlParameter[] parameters = parameterList.ToArray();
dbb.Database.ExecuteSqlCommand(sql, parameters);
Check the Field length of the column you are trying to put the data into.
I have had this problem before where the column was varchar(10) and I was trying to concatenate two char strings of 6 characters each. Making them 12 characters long. 2 longer than the target field.
Your problem might be similar.

Update Sql query where data is comming from 2 tables

I need to know that i have 3 tables one with sessional marks with primary key sessional id and another table student with student id as primary key and third table Data with student id and sessional id as foreign keys.
Now i need to update marks of each student in grid view so that marks get stored in sessional marks table.
i am using this query
string hourly1;
string hourly2;
string student_id;
for (int i = 0; i < this.dataGridView1.Rows.Count - 1; i++)
{
hourly1 = dataGridView1[1,i].Value.ToString();
hourly2 = dataGridView1[2,i].Value.ToString();
student_id = Convert.ToString(dataGridView1[3, i].Value);
SqlCommand cmd = new SqlCommand("UPDATE SessionalMarks SET " +
"SessionalMarks.Hourly1Marks = '" + hourly1 + "'," + "SessionalMarks.Hourly2Marks = '" + hourly2 + "'from Student,DATA where Student.StudentId=DATA.StudentId AND Student.StudentId='" + student_id + "'", conn);
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
but this query is adding same marks in each row in need to update marks which are placed in the grid view
i think there is a problem in where clause can some one help me please.
It's very unclear what your SQL schema looks like, but in your update statement, everything after FROM isn't being used for any purpose. Your WHERE clause doesn't mention SessionalMarks, so each time you loop through your for loop you're updating all rows in that table.
If you post your SQL schema of these three tables, it might help us understand the shape of your data and help you write a better query. The way you've described it, it sounds like the DATA table ought to contain the marks for each student, but you've apparently put that data in the SessionalMarks table instead.
However, your code has some problems besides the one you've mentioned:
You're composing a SQL query by joining strings together, and it looks like those strings might have come from the user. This exposes you to a SQL injection attack, or at least if the user types a ' your program will behave incorrectly.
You're opening and closing the database connection repeatedly, instead of opening it once and closing it when you're finished.
To fix these problems, you probably should (a) use a parameterized SQL query, and (b) open and close the database connection outside of the loop.
This isn't perfect, but it's a start:
// this query needs to be fixed
string query = #"UPDATE SessionalMarks
SET SessionalMarks.Hourly1Marks = #hourly1
,SessionalMarks.Hourly2Marks = #hourly2
FROM Student,DATA
WHERE Student.StudentId = DATA.StudentId
AND Student.StudentId = #studentid";
// Make sure we dispose of the SqlCommand when we're finished with it
using (SqlCommand cmd = new SqlCommand(query, conn))
{
// Create my three parameters, don't need a value yet
// Need to make sure we have the right SqlDbType specified
cmd.Parameters.Add( new SqlParameter("#hourly1", SqlDbType.Decimal) );
cmd.Parameters.Add( new SqlParameter("#hourly2", SqlDbType.Decimal) );
cmd.Parameters.Add( new SqlParameter("#studentid", SqlDbType.Int) );
conn.Open();
try
{
// For each row in our DataGridView
// We could also use foreach(DataGridViewRow row in dataGridView1.Rows)
for (int i = 0; i < this.dataGridView1.Rows.Count - 1; i++)
{
// Fill in our parameters with our values
cmd.Parameters[0].Value = dataGridView1[1,i].Value.ToString();
cmd.Parameters[1].Value = dataGridView1[2,i].Value.ToString();
cmd.Parameters[2].Value = Convert.ToString(dataGridView1[3, i].Value);
cmd.ExecuteNonQuery();
}
}
finally
{
// Close our database connection even if cmd.ExecuteNonQuery() throws
conn.Close();
}
}

How to bulk insert geography into a new sql server 2008 table

I have a very large shape file with hundreds of thousands of rows of polygons and other associated data, like formatted addressing and APN numbers. How do I get this data into a table with geography without using things like Shape2SQL? I can't very well run an insert statement for every row that would take forever, the optimal solution would be to create a csv or a properly formatted bin file and then do a bulk insert, or bcp, or openrowset, but try, try, try as I might I cannot get a csv file or bin file to work. Can anybody help?
The following code is the best I could manage.
SqlGeographyBuilder sql_geography_builder = new SqlGeographyBuilder();
sql_geography_builder.SetSrid(4326);
sql_geography_builder.BeginGeography(OpenGisGeographyType.Polygon);
sql_geography_builder.BeginFigure(-84.576064, 39.414853);
sql_geography_builder.AddLine(-84.576496, 39.414800);
sql_geography_builder.AddLine(-84.576522, 39.414932);
sql_geography_builder.AddLine(-84.576528, 39.414964);
sql_geography_builder.AddLine(-84.576095, 39.415015);
sql_geography_builder.AddLine(-84.576064, 39.414853);
sql_geography_builder.EndFigure();
sql_geography_builder.EndGeography();
SqlGeography sql_geography = new SqlGeography();
sql_geography = sql_geography_builder.ConstructedGeography;
FileStream file_stream = new FileStream("C:\\PROJECTS\\test.bin", FileMode.Create);
BinaryWriter binary_writer = new BinaryWriter(file_stream);
sql_geography.Write(binary_writer);
binary_writer.Flush();
binary_writer.Close();
file_stream.Close();
file_stream.Dispose();
SqlConnection sql_connection = new SqlConnection(connection_string);
sql_connection.Open();
SqlCommand sql_command = new SqlCommand();
sql_command.Connection = sql_connection;
sql_command.CommandTimeout = 0;
sql_command.CommandType = CommandType.Text;
sql_command.CommandText = "INSERT INTO [SPATIAL_TEST].[dbo].[Table_1] ([geo]) " +
"SELECT [ors].* " +
"FROM OPENROWSET(BULK 'C:\\PROJECTS\\AMP\\test.bin', SINGLE_BLOB) AS [ors] ";
sql_command.ExecuteNonQuery();
sql_command.Dispose();
sql_connection.Close();
sql_connection.Dispose();
But this only lets me import singularly the polygon--I need everything else as well.
Well after several days of headache I have come to the conclusion that there is no answer. Not even the mighty ESRI has any clue. Thankfully I did come up with a different soultion. In my table definition I created an NVARCHAR(MAX) column to hold the WFT of my geography and added that WFT to my csv file, and then after the bulk insert I run a table wide update statment to convert tht WFT to the actual geography type. Also adjust the csv file to use a different character besides a , to separate with becuase the WFT contains ,'s
SqlGeographyBuilder sql_geography_builder = new SqlGeographyBuilder();
sql_geography_builder.SetSrid(4326);
sql_geography_builder.BeginGeography(OpenGisGeographyType.Polygon);
sql_geography_builder.BeginFigure(-84.576064, 39.414853);
sql_geography_builder.AddLine(-84.576496, 39.414800);
sql_geography_builder.AddLine(-84.576522, 39.414932);
sql_geography_builder.AddLine(-84.576528, 39.414964);
sql_geography_builder.AddLine(-84.576095, 39.415015);
sql_geography_builder.AddLine(-84.576064, 39.414853);
sql_geography_builder.EndFigure();
sql_geography_builder.EndGeography();
SqlGeography sql_geography = new SqlGeography();
sql_geography = sql_geography_builder.ConstructedGeography;
StreamWriter stream_writer = new StreamWriter("C:\\PROJECTS\\AMP\\test.csv");
stream_writer.AutoFlush = true;
stream_writer.WriteLine("1?123 TEST AVE?" + sql_geography.ToString() + "?");
stream_writer.Flush();
stream_writer.WriteLine("2?456 TEST AVE?" + sql_geography.ToString() + "?");
stream_writer.Flush();
stream_writer.WriteLine("9?789 TEST AVE?" + sql_geography.ToString() + "?");
stream_writer.Flush();
stream_writer.Close();
stream_writer.Dispose();
SqlConnection sql_connection = new SqlConnection(STRING_SQL_CONNECTION);
sql_connection.Open();
SqlCommand sql_command = new SqlCommand();
sql_command.Connection = sql_connection;
sql_command.CommandTimeout = 0;
sql_command.CommandType = CommandType.Text;
sql_command.CommandText = "BULK INSERT [SPATIAL_TEST].[dbo].[Table_1] " +
"FROM 'C:\\PROJECTS\\AMP\\test.csv' " +
"WITH (FIELDTERMINATOR = '?', ROWTERMINATOR = '\n') " +
"" +
"UPDATE [SPATIAL_TEST].[dbo].[Table_1] " +
"SET [geo] = geography::STPolyFromText([geo_string], 4326) ";
sql_command.ExecuteNonQuery();
sql_command.Dispose();
sql_connection.Close();
sql_connection.Dispose();
MessageBox.Show("DONE");
}
catch (Exception ex)
{ MessageBox.Show(ex.Message); }

Is it possible to run native sql with entity framework?

I am trying to search an XML field within a table, This is not supported with EF.
Without using pure Ado.net is possible to have native SQL support with EF?
For .NET Framework version 4 and above: use ObjectContext.ExecuteStoreCommand() if your query returns no results, and use ObjectContext.ExecuteStoreQuery if your query returns results.
For previous .NET Framework versions, here's a sample illustrating what to do. Replace ExecuteNonQuery() as needed if your query returns results.
static void ExecuteSql(ObjectContext c, string sql)
{
var entityConnection = (System.Data.EntityClient.EntityConnection)c.Connection;
DbConnection conn = entityConnection.StoreConnection;
ConnectionState initialState = conn.State;
try
{
if (initialState != ConnectionState.Open)
conn.Open(); // open connection if not already open
using (DbCommand cmd = conn.CreateCommand())
{
cmd.CommandText = sql;
cmd.ExecuteNonQuery();
}
}
finally
{
if (initialState != ConnectionState.Open)
conn.Close(); // only close connection if not initially open
}
}
Using Entity Framework 5.0 you can use ExecuteSqlCommand to execute multi-line/multi-command pure SQL statements. This way you won't need to provide any backing object to store the returned value since the method returns an int (the result returned by the database after executing the command).
Sample:
context.Database.ExecuteSqlCommand(#
"-- Script Date: 10/1/2012 3:34 PM - Generated by ExportSqlCe version 3.5.2.18
SET IDENTITY_INSERT [Students] ON;
INSERT INTO [Students] ([StudentId],[FirstName],[LastName],[BirthDate],[Address],[Neighborhood],[City],[State],[Phone],[MobilePhone],[Email],[Enrollment],[Gender],[Status]) VALUES (12,N'First Name',N'SecondName',{ts '1988-03-02 00:00:00.000'},N'RUA 19 A, 60',N'MORADA DO VALE',N'BARRA DO PIRAÍ',N'Rio de Janeiro',N'3346-7125',NULL,NULL,{ts '2011-06-04 21:25:26.000'},2,1);
INSERT INTO [Students] ([StudentId],[FirstName],[LastName],[BirthDate],[Address],[Neighborhood],[City],[State],[Phone],[MobilePhone],[Email],[Enrollment],[Gender],[Status]) VALUES (13,N'FirstName',N'LastName',{ts '1976-04-12 00:00:00.000'},N'RUA 201, 2231',N'RECANTO FELIZ',N'BARRA DO PIRAÍ',N'Rio de Janeiro',N'3341-6892',NULL,NULL,{ts '2011-06-04 21:38:38.000'},2,1);
");
For more on this, take a look here: Entity Framework Code First: Executing SQL files on database creation
For Entity Framework 5 use context.Database.SqlQuery.
And for Entity Framework 4 use context.ExecuteStoreQuery
the following code:
public string BuyerSequenceNumberMax(int buyerId)
{
string sequenceMaxQuery = "SELECT TOP(1) btitosal.BuyerSequenceNumber FROM BuyerTakenItemToSale btitosal " +
"WHERE btitosal.BuyerID = " + buyerId +
"ORDER BY CONVERT(INT,SUBSTRING(btitosal.BuyerSequenceNumber,7, LEN(btitosal.BuyerSequenceNumber))) DESC";
var sequenceQueryResult = context.Database.SqlQuery<string>(sequenceMaxQuery).FirstOrDefault();
string buyerSequenceNumber = string.Empty;
if (sequenceQueryResult != null)
{
buyerSequenceNumber = sequenceQueryResult.ToString();
}
return buyerSequenceNumber;
}
To return a List use the following code:
public List<PanelSerialList> PanelSerialByLocationAndStock(string locationCode, byte storeLocation, string itemCategory, string itemCapacity, byte agreementType, string packageCode)
{
string panelSerialByLocationAndStockQuery = "SELECT isws.ItemSerialNo, im.ItemModel " +
"FROM Inv_ItemMaster im " +
"INNER JOIN " +
"Inv_ItemStockWithSerialNoByLocation isws " +
" ON im.ItemCode = isws.ItemCode " +
" WHERE isws.LocationCode = '" + locationCode + "' AND " +
" isws.StoreLocation = " + storeLocation + " AND " +
" isws.IsAvailableInStore = 1 AND " +
" im.ItemCapacity = '" + itemCapacity + "' AND " +
" isws.ItemSerialNo NOT IN ( " +
" Select sp.PanelSerialNo From Special_SpecialPackagePriceForResale sp " +
" Where sp.PackageCode = '" + packageCode + "' )";
return context.Database.SqlQuery<PanelSerialList>(panelSerialByLocationAndStockQuery).ToList();
}
Keep it simple
using (var context = new MyDBEntities())
{
var m = context.ExecuteStoreQuery<MyDataObject>("Select * from Person", string.Empty);
//Do anything you wonna do with
MessageBox.Show(m.Count().ToString());
}
public class RaptorRepository<T>
where T : class
{
public RaptorRepository()
: this(new RaptorCoreEntities())
{
}
public RaptorRepository(ObjectContext repositoryContext)
{
_repositoryContext = repositoryContext ?? new RaptorCoreEntities();
_objectSet = repositoryContext.CreateObjectSet<T>();
}
private ObjectContext _repositoryContext;
private ObjectSet<T> _objectSet;
public ObjectSet<T> ObjectSet
{
get
{
return _objectSet;
}
}
public void DeleteAll()
{
_repositoryContext
.ExecuteStoreCommand("DELETE " + _objectSet.EntitySet.ElementType.Name);
}
}
So what do we say about all this in 2017? 80k consultations suggests that running a SQL request in EF is something a lot of folk want to do. But why? For what benefit?
Justin, a guru with 20 times my reputation, in the accepted answer gives us a static method that looks line for line like the equivalent ADO code. Be sure to copy it well because there are a few subtleties to not get wrong. And you're obliged to concatenate your query with your runtime parameters since there's no provision for proper parameters. So all users of this method will be constructing their SQL with string methods (fragile, untestable, sql injection), and none of them will be unit testing.
The other answers have the same faults, only moreso. SQL buried in double quotes. SQL injection opportunities liberally scattered around. Esteemed peers, this is absolutely savage behaviour. If this was C# being generated, there would be a flame war. We don't even accept generating HTML this way, but somehow its OK for SQL. I know that query parameters were not the subject of the question, but we copy and reuse what we see, and the answers here are both models and testaments to what folk are doing.
Has EF melted our brains? EF doesn't want you to use SQL, so why use EF to do SQL.
Wanting to use SQL to talk to a relational DB is a healthy, normal impulse in adults. QueryFirst shows how this could be done intelligently, your sql in .sql file, validated as you type, with intellisense for tables and columns. The C# wrapper is generated by the tool, so your queries become discoverable in code, with intellisense for your inputs and results. End to end strong typing, without ever having to worry about a type. No need to ever remember a column name, or its index. And there are numerous other benefits... The temptation to concatenate is removed. The possibility of mishandling your connections also. All your queries and the code that accesses them are continuously integration-tested against your dev DB. Schema changes in your DB pop up as compile errors in your app. We even generate a self test method in the wrapper, so you can test new versions of your app against existing production databases, rather than waiting for the phone to ring. Anyone still need convincing?
Disclaimer: I wrote QueryFirst :-)